How to save a list of dataframes to csv

江枫思渺然 提交于 2021-02-20 03:51:46

问题


I have a list of data frames which I reshuffle and then I want to save the output as a csv. To do this I'm trying to append this list to an empty data frame:

l1=[year1, year2,..., year30]
shuffle (l1)
columns=['year', 'day', 'tmin', 'tmax', 'pcp']
index=np.arange(10957)
df2=pd.DataFrame(columns=columns, index=index)
l1.append(df2)

This result in an empty data frames with a bunch of Nans. I don't necessarily need to append my reshuffled list to a dataframe, I just need to save it as a csv, and this is the only way I find yet.


回答1:


I think you need concat with to_csv if l1 is list of DataFrames:

print pd.concat(l1).to_csv('filename')



回答2:


An alternative to the chosen answer is to open the CSV and append one dataframe at a time inside a loop. This can be order of magnitude faster depending on the size of data.

f = open(filename, 'a')
for df in l1:
    df.to_csv(f)
f.close()


来源:https://stackoverflow.com/questions/36872851/how-to-save-a-list-of-dataframes-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!