Multiple pandas.dataframe to one csv file

假如想象 提交于 2020-06-08 02:59:09

问题


I have multiple pandas dataframes, and hope to write them as one CSV file. What is the most straightforward way?

For example, from following four dataframes,

enter image description here

how can I create below CSV?

enter image description here

Note The dataframes all have the same dimensions.


回答1:


A very straightforward way would be to concat pairs horizontally, concat the results vertically, and write it all out using 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.



来源:https://stackoverflow.com/questions/30829748/multiple-pandas-dataframe-to-one-csv-file

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