How to select dataframe rows using a condition with pandas in python ?

How to select dataframe rows using a condition with pandas in python ?

Daidalos May 24, 2020


Examples of how to select a dataframe rows using a condition with pandas in python:

1 -- Create a simple dataframe

Lets start by creating a simple dataframe with pandas:

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

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

2 -- Select dataframe rows using a condition

Example lets select the rows where the column named 'sex' is equal to 1:

>>> df[ df['Sex'] == 1 ]
   Age   Name  Sex
0   20    Ben    1
3   30    Tom    1
4   12   John    1
5   21  Steve    1

3 -- Select dataframe rows using two conditions

Another example using two conditions with & (and):

>>> df[ (df['Sex'] == 1) & (df['Age'] < 25 )]
   Age   Name  Sex
0   20    Ben    1
4   12   John    1
5   21  Steve    1

4 -- References