typestar

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

  1. and does not work on Series — use & with parentheses.
  2. isin replaces a chain of equality checks.
  3. query reads better when the expression gets long.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Selecting rows, step 7 of 26 in pandas.

← Previous Next →