typestar

List columns in Python

A column can hold lists, and the list namespace works on them element-wise.

import polars as pl

frame = pl.DataFrame({
    "lang": ["python", "rust"],
    "tours": [["basics", "pandas", "sklearn"], ["basics", "traits"]],
})

print(frame.with_columns(
    pl.col("tours").list.len().alias("count"),
    pl.col("tours").list.first().alias("first"),
    pl.col("tours").list.join(", ").alias("joined"),
))
print(frame.explode("tours"))

How it works

  1. group_by().agg without a reducer produces list columns.
  2. list.len, list.first and list.eval operate inside each list.
  3. explode turns each element back into its own row.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
337
Tokens
145
Three-star pace
110 tpm

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

Type this snippet

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

← Previous Next →