简体   繁体   中英

How to write data to existing excel file using pandas?

I want to request some data from a python module 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. I notice that pandas is already built in tushare. How to put the data together and generate only one excel file?

    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 .

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM