How to remove dataframe rows where a condition is true with pandas in python ?

How to remove dataframe rows where a condition is true with pandas in python ?

Daidalos June 16, 2020


Examples of how to drop dataframe rows where a condition is true with pandas in python

1 -- Create a dataframe

Lets consider for example the following dataframe:

>>> import pandas as pd
>>> data = {'Name':['Ben','Anna','Zow','Tom','John','Steve'], 'Age':[20,27,43,30,12,21], 'Sex':[1,0,0,1,1,1]}
>>> df = pd.DataFrame(data)

returns here:

>>> df
   Age   Name  Sex
0   20    Ben    1
1   27   Anna    0
2   43    Zoe    0
3   30    Tom    1
4   12   John    1
5   21  Steve    1

2 -- Drop rows using a single condition

To drop rows for example where the column Sex is equal to 1, a solution is to do:

>>> df.drop( df[ df['Sex'] == 1 ].index, inplace=True)

returns

   Name  Age  Sex
1  Anna   27    0
2   Zoe   43    0

3 -- Drop rows using two conditions

Another exemple using two conditions: drop rows where Sex = 1 and Age < 25:

df.drop( df[ (df['Sex'] == 1) & (df['Age'] < 25) ].index, inplace=True)

returns

   Name  Age  Sex
1  Anna   27    0
2   Zoe   43    0
3   Tom   30    1

4 -- References