How to filter dataframe rows using a OR statement with pandas ?

Active February 21, 2022    /    Viewed 153    /    Comments 0    /    Edit


Examples of how to filter dataframe rows using multiple conditions with OR in pandas:

Create a dataframe with pandas

Let's first create a dataframe with pandas using a dictionary:

import pandas as pd
import numpy as np

data= {'A':[-1,-2,3,4,5],
       'B':[6,-7,8,9,-10],
       'C':[11,12,13,14,15],}

df = pd.DataFrame(data)

returns here

   A   B   C
0 -1   6  11
1 -2  -7  12
2  3   8  13
3  4   9  14
4  5 -10  15

Filter using one column

To filter a dataframe with a OR statement, a solution is to use the logical operator |

df[ (df['A'] < 0) | (df['A'] > 4) ]

returns here

   A   B   C
0 -1   6  11
1 -2  -7  12
4  5 -10  15

Filter using two different columns

Another example using two different columns

df[ (df['A'] < 0) | (df['B'] < 0) ]

returns

   A   B   C
0 -1   6  11
1 -2  -7  12
4  5 -10  15

More than two columns

Another example using more than two different columns

df[ (df['A'] < 0) | (df['B'] < 0) | (df['C'] >= 14) ]

returns

   A   B   C
0 -1   6  11
1 -2  -7  12
3  4   9  14
4  5 -10  15

Multiple conditions witn OR and AND

df[  (df['A'] < 0) | (df['B'] < 0)  & (df['C'] == 11) ]

returns

     A  B   C
0 -1  6  11
1 -2 -7  12

Same as

df[  (df['A'] < 0) | ( (df['B'] < 0)  & (df['C'] == 11) )  ]

returns

     A  B   C
0 -1  6  11
1 -2 -7  12

or

cond1 = (df['A'] < 0)
cond2 = (df['B'] < 0)  & (df['C'] == 11)

df[ cond1 | cond2 ]

returns

     A  B   C
0 -1  6  11
1 -2 -7  12

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