Home > other >  Pandas merge only on where condition
Pandas merge only on where condition

Time:08-25

Please help with logic on applying merge function only where condition is met.

In below example: merge should be applicable only when, np.where name = John, else show 0

df1 = pd.DataFrame({'Name': ['John', 'Tom', 'Simon', 'Jose'], 
                    'Age': [5, 6, 4, 5]})



df2 = pd.DataFrame({'Name': ['John', 'Tom', 'Jose'],
                    'Class': ['Second', 'Third', 'Fifth']})

Expected result: enter image description here

TIA

CodePudding user response:

use merge and select the good rows of your df2.

df1.merge(df2[df2["Name"] == 'John'] , how = 'left' , on = 'Name')
  • Related