Search code examples
pythonpandasdataframedictionarylines-of-code

Filter a dataframe using values from a dict


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().


Solution

  • 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