Search code examples
pythonpandasdataframenumpyplotly

How to merge two dataframe with some same column name in python?


is there a way i can combine two dataframes which has some column name same but rest different? For example:

df1:
Name age sex
Mary 32  F
Susan 43 f
Robert 34 M

df2:
age sex eyecolor
22  M   Blue
18  M   Brown
33  F   Black

is there a way i can combine these two dataframes with any missing value as 0? expected output:

Name    age sex eyecolor
Mary    32   F   0
Susan   43   f   0
Robert  34   M   0
  0     22   M   Blue
  0     18   M   Brown
  0     33   F   Black

Solution

  • You can use pd.concat with fillna to replace NaN values with 0

    pd.concat([df1,df2]).fillna(0)
    

    Gives:

         Name age sex eyecolor
    0    Mary  32   F        0
    1   Susan  43   f        0
    2  Robert  34   M        0
    0       0  22   M     Blue
    1       0  18   M    Brown
    2       0  33   F    Black