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

Published: February 21, 2022

Updated: December 09, 2022

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

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