Python Team
Python Team

Reputation: 1171

Merge two dataframes in pandas based on the same column name values

I am using pandas to merge two dataframes. I want to add new columns to existing dataframe one as expected the result below. Please kindly help me to do this.

one:

 Name      Status  Dummy
Kumar     Done       1
Shankar   Progress   1
Shankar   Done       2
sekar      no        0

Two:

Name     Status    Remarks  Temp
Shankar   Progress  Good     5
Shankar    Done     Very     6

Expected Result :

  Name    Status     Dummy    Remarks   Temp
  Kumar     Done       1                 0
  Shankar   Progress   1        Good     5
  Shankar   Done       2        very     6
  sekar      no        0                 0

Upvotes: 1

Views: 1954

Answers (1)

jezrael
jezrael

Reputation: 863611

Use left join with merge and then replace missing values by fillna:

df = df1.merge(df2, on=['Name','Status'], how='left')
df['Temp'] = df['Temp'].fillna(0).astype(int)
df['Remarks'] = df['Remarks'].fillna('')

print (df)
      Name    Status  Dummy Remarks  Temp
0    Kumar      Done      1             0
1  Shankar  Progress      1    Good     5
2  Shankar      Done      2    Very     6
3    sekar        no      0             0

Upvotes: 3

Related Questions