简体   繁体   中英

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. 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?

Use 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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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