iT邦幫忙

0

請教dataframe.reindex無效可能原因

各位先進您好,

本人試著撰寫爬蟲程式至證交所取得三大法人資料,其程式碼是取自各先進的sample code,
再試著改寫。
邏輯如下:

  1. 設定一變數來決定要從n天前的資料逐一爬取
  2. 將爬取的主程式段寫在while 迴圈內(配合上步驟的變數)
  3. 因為下載下來的資料並沒有日期欄,故需加工加入一欄stock_date,並給值
    ==> 在此遇到問題,想利用reindx指令於首欄加入stock_date欄並給值一直沒有成功,也沒有出現錯誤訊息 Orz... ,還請各位先進能給予指點><

PS :
待該問題解決後,會再持續加入將每日的dataframe 另外append至一dataframe,以收集每日資至單一dataframe,進而將其匯出電子檔,以供其它程式使用。

==================Code Start==========================
import requests
from io import StringIO
import pandas as pd
import time
import datetime
debug_mode = 'Y'#過程中是否顯示debug訊息
intI = 3 #自n天前的資料開始抓

#逐日爬取資料
while intI >= 0:
#日期格式:yyyymmdd
date = (datetime.date.today() + datetime.timedelta(days=intI*-1)).strftime('%Y%m%d')
if debug_mode == 'Y':
print('==================Begin debug - '+date+'==================')
try:
r = requests.get('http://www.tse.com.tw/fund/T86?response=csv&date='+date+'&selectType=ALLBUT0999')#
df = pd.read_csv(StringIO(r.text), header=1).dropna(how='all', axis=1).dropna(how='any')
col_names = df.columns.tolist()
col_names.insert(0,'stock_date')
df.reindex(columns=col_names,fill_value=date)
if debug_mode == 'Y':
print(df[:1])
print('-------')
print('col_names:')
print(col_names)
print('-------')
print('df columns : ')
print(df.columns)
print('----比對---')
print('col_names數:'+str(len(col_names)))
print('df.columns:'+str(len(df.columns)))
print(str(set(df.columns).difference(set(col_names))))
except ValueError:
if debug_mode == 'Y':
print('no data found')
print('-------')
if debug_mode == 'Y':
print('==================End debug - '+date+'==================')
intI -= 1

==================Code End==========================

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
froce
iT邦大師 1 級 ‧ 2018-08-11 14:59:12

下次麻煩用原始碼區塊來問,尤其python的code和縮排很有關係。

 df.reindex(columns=col_names,fill_value=date)

參閱pandas的說明:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html
Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and copy=False

reindex()會產生一個新的dataframe,並不會改變原本的dataframe。
你可以這樣改你的code

 df = df.reindex(columns=col_names,fill_value=date)

這樣會讓df這個變數重新指向 df.reindex(columns=col_names,fill_value=date)的結果。

Doggww iT邦新手 5 級 ‧ 2018-08-12 08:07:46 檢舉

經先進的指導後確認執行無誤^^~

我要發表回答

立即登入回答