繁体   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