[英]How to write data to existing excel file using pandas?
I want to request some data from a python module tushare. 我想从python模块tushare请求一些数据。 By using this code, I can each time get a line of data.
通过使用此代码,我每次都可以获得一行数据。 However I want to send the server a request for like every 5 seconds and put all the data within 4 hrs into one excel file.
但是我想每隔5秒向服务器发送一次请求,并将所有数据在4小时内放入一个excel文件中。 I notice that pandas is already built in tushare.
我注意到大熊猫已经建立在tushare中。 How to put the data together and generate only one excel file?
如何将数据放在一起并只生成一个excel文件?
import tushare as ts
df=ts.get_realtime_quotes('000875')
df.to_excel(r'C:\Users\stockfile\000875.xlsx')
You can do it with for example 例如,您可以这样做
df = df.append(ts.get_realtime_quotes('000875'))
Given the number of calls, it nay be better to create a data frame and fill it with data rows as they arrive. 考虑到调用次数,创建数据框并在数据到达时用数据行填充它会更好。 Something like this:
像这样的东西:
# 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)
Another way to do it (possibly simpler and without preallocating the empty data frame) would be storing answers from tushare
in a list and then applying pd.concat
. 另一种方法(可能更简单,没有预先分配空数据帧)将在列表中存储来自
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)
This way you don't need to know the number of requests in advance (for example, if you decide to write the for
loop without explicit number of repetitions). 这样您就不需要事先知道请求的数量(例如,如果您决定编写
for
循环而没有明确的重复次数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.