簡體   English   中英

如何使用pandas將數據寫入現有的excel文件?

[英]How to write data to existing excel file using pandas?

我想從python模塊tushare請求一些數據。 通過使用此代碼,我每次都可以獲得一行數據。 但是我想每隔5秒向服務器發送一次請求,並將所有數據在4小時內放入一個excel文件中。 我注意到大熊貓已經建立在tushare中。 如何將數據放在一起並只生成一個excel文件?

    import tushare as ts
    df=ts.get_realtime_quotes('000875')

    df.to_excel(r'C:\Users\stockfile\000875.xlsx')

例如,您可以這樣做

df = df.append(ts.get_realtime_quotes('000875'))

考慮到調用次數,創建數據框並在數據到達時用數據行填充它會更好。 像這樣的東西:

# Here, just getting column names:
columns = ts.get_realtime_quotes('000875').columns
# Choose the right number of calls, N,
df = pd.DataFrame(index = range(N), columns = columns)
for i in range(N):
    df.iloc[0] = ts.get_realtime_quotes('000875').iloc[0]
    sleep(5)

另一種方法(可能更簡單,沒有預先分配空數據幀)將在列表中存儲來自tushare答案,然后應用pd.concat

list_of_dfs = []
for _ in range(N):
    list_of_dfs.append(ts.get_realtime_quotes('000875'))
    sleep(5)
full_df = pd.concat(list_of_dfs)

這樣您就不需要事先知道請求的數量(例如,如果您決定編寫for循環而沒有明確的重復次數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM