Filter and select in Python
Choosing rows and columns from a DataFrame.
import polars as pl
df = pl.DataFrame({
"name": ["ada", "grace", "katherine", "alan"],
"lang": ["python", "python", "rust", "go"],
"score": [95, 88, 92, 81],
})
top = df.filter(pl.col("score") > 90)
pythonists = df.filter(pl.col("lang") == "python")
names = df.select("name", "score")
combo = df.filter(pl.col("score") > 85).select(pl.col("name"))
sorted_df = df.sort("score", descending=True)
How it works
filterkeeps rows matching a predicate.selectkeeps only the named columns.sortorders rows; the two compose freely.
Keywords and builtins used here
as
The run, in numbers
- Lines
- 14
- Characters to type
- 396
- Tokens
- 164
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 94 seconds.
Step 1 of 3 in Filtering & sorting, step 9 of 32 in Polars.