Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query pandas data frame with `or`b boolean? [duplicate]

I have a simple pandas data frame.

import pandas as pd    
x = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
y = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
users =['mark', 'mark', 'mark', 'rachel', 'rachel', 'rachel', 'jeff', 'jeff', 'jeff', 'lauren', 'lauren', 'lauren']

df = pd.DataFrame(dict(x=x, y=y, users=users)

I want to keep certain rows of the data frame. Let's say all "rachels" and "jeffs". I tried df.query:

df=df.query('users=="rachel"' or 'users=="jeff"')

The result is a data frame only with users=="rachel". Is there a way to combine queries?

like image 627
Rachel Avatar asked Aug 26 '26 01:08

Rachel


1 Answers

The standard way would be to use the bitwise or operator |. For a clear explanation of why, I'd suggest checking out this answer. You also need to use parentheses around each condition due to Python's order of evaluation.

df[(df.users == 'rachel') | (df.users == 'jeff')]
    users   x    y
3  rachel  30  200
4  rachel   5  300
5  rachel  10  300
6    jeff  20  400
7    jeff  30  400
8    jeff   5  500

Using query, you can still just use the or operator:

df.query("users=='rachel' | users=='jeff'")
    users   x    y
3  rachel  30  200
4  rachel   5  300
5  rachel  10  300
6    jeff  20  400
7    jeff  30  400
8    jeff   5  500
like image 186
Nick Becker Avatar answered Aug 28 '26 06:08

Nick Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!