Skip to content
Advertisement

Pandas merge only on where condition

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

Advertisement

Answer

use merge and select the good rows of your df2.

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