Home > Mobile >  How to get row if value from one dataframe is in another?
How to get row if value from one dataframe is in another?

Time:10-08

I have two dataframes:

df1 = {'Stream': ['Netflix', 'Hulu', 'YouTube', 'Aprime', 'HBO', 'Peacock', 'Tubi'],
       'Percent': [51, 19, 40, 18, 35, 12, 7]}
df2 = {'Test': ['Hulu', 'Netflix', 'Disney']}

I want to see if they're any instances of df2 in df1. If there are, I then want to print the df1 row. The result I'm looking for:

Stream  Percent
Hulu    19
Netflix 51

I was thinking of something like below, but I can't figure it out:

for row in df1:
    if row['Stream'] == df2['Test']:
       print(row)

CodePudding user response:

Try using isin

df1 = pd.DataFrame(df1)
df2 = pd.DataFrame(df2)
df1[df1["Stream"].isin(df2.Test)]

Out[523]: 
    Stream  Percent
0  Netflix       51
1     Hulu       19

CodePudding user response:

Another way to do this would to use inner join on the 2 data frames -

df2.set_index('Test').join(df1.set_index('Stream'), how='inner')
         Percent
Hulu          19
Netflix       51
  • Related