Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Drop rows with at least a cell having a value in a given list with the .isin pandas.DataFrame method

I’m trying to use the .isin method but I don’t have the expected result.

Here is a minimal reproducible example

import pandas as pd
df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]}, index=['falcon', 'dog'])
print(df)
print(df[df.isin([0, 2])])

It doesn’t delete the row, but replaces the cell by NaN.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For filtering need bolean Series, if check all column get boolean DataFrame:

So if need test if at least one True per row use DataFrame.any, If need test if all True per row use DataFrame.all:

print (df.isin([0, 2]))
        num_legs  num_wings
falcon      True       True
dog        False       True

print (df.isin([0, 2]).any(axis=1))
falcon    True
dog       True
dtype: bool

print (df.isin([0, 2]).all(axis=1))
falcon     True
dog       False
dtype: bool

print(df[df.isin([0, 2]).any(axis=1)])
        num_legs  num_wings
falcon         2          2
dog            4          0

print(df[df.isin([0, 2]).all(axis=1)])
        num_legs  num_wings
falcon         2          2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading