Home > Software design >  How can I combine different dataframes into one csv in Python?
How can I combine different dataframes into one csv in Python?

Time:04-29

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

CodePudding user response:

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")
  • Related