How do I filter a DataFrame column that includes ALL values in a list?

Viewed 38

For instance, the column contains a full product descritpion (e.g. yellow leather sneaker), and I want to select the column based on a list (e.g. ['yellow', 'sneaker']). I tried something like this but obviously it did not work :)

list_to_check = ['yellow', 'sneaker']
df_filtered = df(all(n in df['Column_To_Filter'] for n in list_to_check))

The new df_filtered should includes only rows where ALL the words in the list are included in the same row value of a column (e.g. if the column contains only one of the words, I don't want that column to be shown?)

Any idea?

Thanks in advance!

2 Answers

Try:

list_to_check = ["yellow", "sneaker"]
df_filtered = df[
    df["Column_To_Filter"].apply(lambda x: all(n in x for n in list_to_check))
]
print(df_filtered)

Prints:

         Column_To_Filter
0  yellow leather sneaker

df used:

         Column_To_Filter
0  yellow leather sneaker
1                  yellow

Or try with regex str.contains:

df.loc[df['Column_To_Filter'].str.contains(f'(?={")(?=.*".join(list_to_check)})')]

Output with @AndrejKesely's input data:

         Column_To_Filter
0  yellow leather sneaker
Related