Active February 21, 2022 / Viewed 153 / Comments 0 / Edit
Examples of how to filter dataframe rows using multiple conditions with OR in 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
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
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
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
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
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!