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

Time:10-22

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.

CodePudding user response:

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
  • Related