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:
>>> dfAge Name Sex0 20 Ben 11 27 Anna 02 43 Zoe 03 30 Tom 14 12 John 15 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 Sex1 Anna 27 02 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 Sex1 Anna 27 02 Zoe 43 03 Tom 30 1
