Struct columns in Python
A struct packs several fields into one column, and unnest spreads them out.
import polars as pl
frame = pl.DataFrame({
"lang": ["python", "rust"],
"tours": [11, 12],
"steps": [299, 181],
})
packed = frame.select(
"lang",
pl.struct("tours", "steps").alias("counts"),
)
print(packed)
print(packed.with_columns(
pl.col("counts").struct.field("steps").alias("steps")).drop("counts"))
print(packed.unnest("counts"))
How it works
pl.structbuilds one from existing columns.struct.fieldreads a single member.unnestturns the struct back into columns.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 16
- Characters to type
- 336
- Tokens
- 132
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 72 seconds.
Step 3 of 3 in Text, lists & structs, step 22 of 32 in Polars.