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
indexstays put, everything else is melted.variable_nameandvalue_namename the new columns.- Long form is what group_by and plotting want.
Keywords and builtins used here
asprint
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.
Step 4 of 5 in Reshaping & joining, step 18 of 32 in Polars.