Search code examples
pythonpython-3.xpandasdataframeseries

How to filter list value in pandas


I'm new to this site and to Python and this question may be a bit basic.

I have a pandas Series that contains a list of elements in each row and I am trying to filter each list to only keep the elements in a given list.

reference_list = [item_a, item_c]

index       answers
 1       [item_a, item_b, item_c]
 2       [item_c, item_d, item_e]
 3       [item_a, item_c, item_b]

The output I am looking for would look like this

index       answers
 1       [item_a, item_c]
 2       [item_c]
 3       [item_a, item_c]

So far I have tried for loops, pd.Series.apply(lambda x:) functions and comprehension lists but I did not get the result I needed.

If anyone could give me further insights on my mistakes I would really appreciate it.


Solution

  • Check map with list check

    df['new'] = df.answers.map(lambda x : [y for y in x if y in reference_list])