Nabih Bawazir
Nabih Bawazir

Reputation: 7275

How do I filter based on other dataframe

Here's my data I df

Id   Food
1    Apple
1    Banana
2    Banana
2    Cherry
3    Banana
4    DragonFruit

The other dataset df2

Id
2
4

The result will be

Id   Food
2    Banana
2    Cherry
4    DragonFruit

Here's my code

df2['one'] = 1
df = df.merge(df2, on='Id', how='left')
df = df[df['one'] == 1]
df= df.drop_duplicates()
df = df[['Id' , 'Food']]

It works, but I guess there's exist better method

Upvotes: 2

Views: 80

Answers (2)

sacuL
sacuL

Reputation: 51425

As an alternate solution, you could continue to use merge, without the left argument (i.e. do an inner merge):

df.merge(df2, on='Id')

   Id         Food
0   2       Banana
1   2       Cherry
2   4  DragonFruit

Upvotes: 1

jezrael
jezrael

Reputation: 863541

I think need isin with column Id from df2:

df = df[df['Id'].isin(df2['Id'])]
print (df)
   Id         Food
2   2       Banana
3   2       Cherry
5   4  DragonFruit

Upvotes: 2

Related Questions