[英]Multiple pandas.dataframe to one csv file
I have multiple pandas dataframes, and hope to write them as one CSV file.我有多个 Pandas 数据框,希望将它们写成一个 CSV 文件。 What is the most straightforward way?
最直接的方法是什么?
For example, from following four dataframes,例如,从以下四个数据帧,
how can I create below CSV?如何在 CSV 下创建?
Note The dataframes all have the same dimensions.注意数据框都具有相同的维度。
A very straightforward way would be to concat
pairs horizontally, concat the results vertically, and write it all out using to_csv
:一个非常简单的方法是水平
concat
对,垂直连接结果,然后使用to_csv
将其全部写出来:
import pandas as pd
pd.concat([
pd.concat([df1, df2], axis=1),
pd.concat([df3, df4], axis=1)]).to_csv('foo.csv')
A possibly more memory-conserving way would be to write it piecemeal:一种可能更节省内存的方法是零碎地编写它:
with open('foo.csv', 'w') as f:
pd.concat([df1, df2], axis=1).to_csv(f)
with open('foo.csv', 'a') as f:
pd.concat([df3, df4], axis=1).to_csv(f, header=False)
Omitting headers=False
would repeat the headers.省略
headers=False
将重复标题。
For anyone that needs to append multiple dataframes to same csv vertically, you can use this:对于需要将多个数据帧垂直附加到同一个 csv 的任何人,您可以使用:
with open('all_dfs.csv','a') as f:
for df in list_of_dfs:
df.to_csv(f)
f.write("\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.