typestar

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

  1. pl.struct builds one from existing columns.
  2. struct.field reads a single member.
  3. unnest turns the struct back into columns.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Text, lists & structs, step 22 of 32 in Polars.

← Previous Next →