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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With