typestar

Unpivoting in Python

unpivot is the inverse: wide columns become variable and value rows.

import polars as pl

wide = pl.DataFrame({
    "day": ["mon", "tue"],
    "python": [104, 91],
    "rust": [98, 88],
})

long = wide.unpivot(index="day", variable_name="lang", value_name="tpm")
print(long)
print(long.group_by("lang").agg(pl.col("tpm").mean()).sort("lang"))

How it works

  1. index stays put, everything else is melted.
  2. variable_name and value_name name the new columns.
  3. Long form is what group_by and plotting want.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
261
Tokens
109
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 4 of 5 in Reshaping & joining, step 18 of 32 in Polars.

← Previous Next →