1

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?

2
  • 2
    If your data frames are different (different # of columns and different indexes) then no, not a good idea to put them all in the same csv. You'll just make the life of whoever will read that csv so much harder for nothing Commented Aug 5, 2019 at 14:30
  • 3
    can you just save them as different sheets of an excel file? Commented Aug 5, 2019 at 14:30

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.