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

Time:09-28

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

CodePudding user response:

You can use pd.concat will 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

CodePudding user response:

Another possible solution, based on pandas.merge:

df1.merge(df2, on=['age', 'sex'], how='outer').fillna(0) 

Output:

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