多个 pandas.dataframe 到一个 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30829748/
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
Multiple pandas.dataframe to one csv file
提问by rkjt50r983
I have multiple pandas dataframes, and hope to write them as one CSV file. What is the most straightforward way?
我有多个 Pandas 数据框,希望将它们写成一个 CSV 文件。最直接的方法是什么?
For example, from following four dataframes,
例如,从以下四个数据帧,


how can I create below CSV?
如何在 CSV 下方创建?


NoteThe dataframes all have the same dimensions.
注意数据框都具有相同的维度。
回答by Ami Tavory
A very straightforward way would be to concatpairs 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=Falsewould repeat the headers.
省略headers=False将重复标题。

