pandas merge query "_merge='left_only'" 1

pandas merge query “_merge=’left_only'”

d = (
    df1.merge(df2, 
              on=['c', 'l'],
              how='left', 
              indicator=True)
    .query('_merge == "left_only"')
    .drop(columns='_merge')
)

print(d)
   c  k  l
0  A  1  a
2  B  2  a
4  C  2  d

Here is what the above code is Doing:
1. Merge the two dataframes on columns ‘c’ and ‘l’
2. Use ‘left’ join so that we keep all rows from df1
3. Add a column called ‘_merge’ that indicates the source of each row
4. Filter the dataframe to keep only rows where the ‘_merge’ column is ‘left_only’
5. Drop the ‘_merge’ column

Similar Posts