Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I combine different dataframes into one csv in Python?

I have 2 dataframes with different columns. And I want to combine those into 1 csv file. Both headers should be included and there shouldn’t be empty value if columns aren’t matched.

df1: Test1|Test2|Test3
       1  |  2  | 3

df2: Test4|Test5|Test6
       4  |  5  | 6

I tried to use pd.concat, but I need the result to be like below:

Test1|Test2|Test3
  1  |  2  | 3
Test4|Test5|Test6
  4  |  5  | 6

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do this using Pandas to_csv and setting the mode parameter to "a" for the second DataFrame to avoid overwriting the contents.

df1.to_csv("output.csv", index=False)
df2.to_csv("output.csv", index=False, mode="a")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading