简体   繁体   English

如何将数据帧列表保存到csv

[英]How to save a list of dataframes to csv

I have a list of data frames which I reshuffle and then I want to save the output as a csv. 我有一个数据帧列表,我对其进行了改组,然后将输出另存为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. 这导致带有一堆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. 我不一定需要将重新排列后的列表添加到数据框,我只需要将其保存为csv,这是我找到的唯一方法。

我认为你需要concatto_csv如果l1listDataFrames

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

An alternative to the chosen answer is to open the CSV and append one dataframe at a time inside a loop. 所选答案的替代方法是打开CSV并在循环内一次附加一个数据帧。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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