Boolean filtering in Python
A boolean Series selects rows; combine conditions with & and |, in brackets.
import pandas as pd
frame = pd.DataFrame({
"lang": ["python", "rust", "sql", "css"],
"tpm": [104, 98, 88, 79],
"stars": [3, 3, 2, 1],
})
print(frame[(frame["tpm"] > 85) & (frame["stars"] >= 2)])
print(frame[frame["lang"].isin(["rust", "sql"])])
print(frame.query("tpm > 90 and stars == 3"))
print(frame[~frame["lang"].str.startswith("c")].shape)
How it works
anddoes not work on Series — use&with parentheses.isinreplaces a chain of equality checks.queryreads better when the expression gets long.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 12
- Characters to type
- 347
- Tokens
- 151
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 86 seconds.
Step 3 of 4 in Selecting rows, step 7 of 26 in pandas.