[英]How to output multiple pandas dataframes to the same csv or excel with different dimensions
So I have multiple data tables saved as pandas dataframes, and I want to output all of them into the same CSV for ease of access. 因此,我将多个数据表另存为pandas数据框,并且我想将所有数据表都输出到同一CSV中,以便于访问。 However, I am not really sure the best way to go about this, as I want to maintain each dataframes inherent structure (ie columns and index), so I cant combine them all into 1 single dataframe. 但是,我不确定如何做到这一点的最佳方法,因为我想维护每个数据框的固有结构(即列和索引),因此我无法将它们全部合并为一个单个数据框。
Is there a method by which I can write them all at once with ease, akin the the usual pd.to_csv method? 有没有一种方法可以像通常的pd.to_csv方法那样轻松地一次将它们全部写入?
Use mode='a'
: 使用mode='a'
:
df = pd.DataFrame(np.random.randint(0,100,(4,4)))
df1 = pd.DataFrame(np.random.randint(0,500,(5,5)))
df.to_csv('out.csv')
df1.to_csv('out.csv', mode='a')
!type out.csv !输入out.csv
Output: 输出:
,0,1,2,3
0,0,0,36,53
1,5,38,17,79
2,4,42,58,31
3,1,65,41,57
,0,1,2,3,4
0,291,358,119,267,430
1,82,91,384,398,99
2,53,396,121,426,84
3,203,324,262,452,47
4,127,131,460,356,180
For Excel you can do: 对于Excel,您可以执行以下操作:
from pandas import ExcelWriter
frames = [df1, df2, df3]
saveFile = 'file.xlsx'
writer = ExcelWriter(saveFile)
for x in range(len(frames)):
sheet_name = 'sheet' + str(x+1)
frames[x].to_excel(writer, sheet_name)
writer.save()
You should now have all of your dataframes in 3 different sheets: sheet1, sheet2 and sheet3. 现在,您应该将所有数据框放在3个不同的工作表中:sheet1,sheet2和sheet3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.