Search code examples
pythonpandasnumpydataframequerying

Get all rows from a dataframe, which have matching values from another data frame


I have two data frames, take the example below

df1

userid| name  
    33|  Paul   
    2 |  jack   
    32|  Ryan   

df2

userid| sport | song 
79 |  tennis  | lovelies  
33 |  swimmin | Beatles  
21 |  boxing  | stones  

how would I get a df3, where if the userids match between df1, and df2, I want to df3 to contain only those rows from df2 where they matched with df1

I don't think a JOIN is the answer here, because I want ONLY the rows from df2. not the rows from df1.

Thanks!


Solution

  • use pandas.Series.isin

    df2[df2['userid'].isin(df1['userid'])]
    

    output

       userid      sport        song 
    1      33    swimmin    Beatles