pandas 如何将数据框列表保存到 csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36872851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:07:48  来源:igfitidea点击:

How to save a list of dataframes to csv

pythonlistpandasdataframeexport-to-csv

提问by Sergey Gulbin

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:

我有一个我重新洗牌的数据帧列表,然后我想将输出保存为 csv。为此,我尝试将此列表附加到空数据框中:

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.

这导致带有一堆 Nans 的空数据帧。我不一定需要将改组后的列表附加到数据帧中,我只需要将其另存为 csv,这是我找到的唯一方法。

回答by jezrael

I think you need concatwith to_csvif l1is listof DataFrames:

我认为你需要concatto_csv,如果l1listDataFrames

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

回答by computerist

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.

所选答案的替代方法是打开 CSV 并在循环内一次附加一个数据帧。根据数据的大小,这可以快几个数量级。

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