typestar

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

  1. on names the column whose values become headers.
  2. index is what stays as rows.
  3. aggregate_function resolves collisions.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Reshaping & joining, step 17 of 32 in Polars.

← Previous Next →