Skip to content
Advertisement

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

Advertisement

Answer

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")
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement