filtering rows of a data frame based on whether or not a column's content is in a list

I want to filter a data frame based on whether they are in a list or not:

my_list = [1, 2, 3]
df[df['class'] in my_list]


lib\site-packages\pandas\core\generic.py:1527, in NDFrame.__nonzero__(self)
   1525 @final
   1526 def __nonzero__(self):
-> 1527     raise ValueError(
   1528         f"The truth value of a {type(self).__name__} is ambiguous. "
   1529         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1530     )

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

I was expecting a data frame which only has classes of my_list

>Solution :

You can use the isin() method.

df[df['class'].isin(my_list)]

Leave a Reply