如何使用pandas将数据写入现有的Excel文件?

我想从一个Python模块tushare请求一些数据。 通过使用这个代码,我可以每次获得一行数据。 不过,我想每隔5秒向服务器发送一个请求,并将所有数据在4小时内放入一个excel文件中。 我注意到pandas已经build在了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')) 

鉴于调用的数量,最好创build一个数据框,并在数据到达时填充数据行。 像这样的东西:

 # 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循环而没有明确的重复次数)。