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

Active May 24, 2020    /    Viewed 6783    /    Comments 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount