Filter a dataframe using values from a dict

Question:

I have a dataframe DF, I want to filter rows based on values on a dictionary

fruits = {'BN':'Banana', 'LM': 'Lemon', 'AP':'Apple', 'MG': 'Mango'}

I tried the following, but it didn’t work

df = df.loc[df['FruitName'] in fruits.values()]

I get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Asked By: dxtr

||

Answers:

You can use .isin():

df = df[df["FruitName"].isin(fruits.values())]
print(df)

Prints:

  FruitName
0     Lemon
2     Mango

Dataframe used:

    FruitName
0       Lemon
1  Grapefruit
2       Mango
Answered By: Andrej Kesely