Pivoting in Python
pivot turns a key column into columns, aggregating where keys repeat.
import polars as pl
frame = pl.DataFrame({
"day": ["mon", "mon", "tue", "tue"],
"lang": ["python", "rust", "python", "sql"],
"tpm": [104, 98, 91, 79],
})
grid = frame.pivot(on="lang", index="day", values="tpm",
aggregate_function="mean")
print(grid)
print(grid.columns)
How it works
onnames the column whose values become headers.indexis what stays as rows.aggregate_functionresolves collisions.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 12
- Characters to type
- 271
- Tokens
- 111
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 61 seconds.
Step 3 of 5 in Reshaping & joining, step 17 of 32 in Polars.