typestar

Adding columns in Python

with_columns evaluates expressions against the frame and returns a new one.

import polars as pl

frame = pl.DataFrame({"chars": [420, 380], "seconds": [60.0, 45.0]})

wider = frame.with_columns(
    (pl.col("chars") / pl.col("seconds")).alias("cps"),
    (pl.col("chars") / 5 / (pl.col("seconds") / 60)).round(1).alias("wpm"),
).with_columns(
    (pl.col("wpm") > 80).alias("fast"),
)

print(wider)
print(frame.columns)

How it works

  1. Several expressions in one call are computed in parallel.
  2. alias names the result; without it the input name is kept.
  3. Nothing mutates: the original frame is untouched.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
331
Tokens
138
Three-star pace
105 tpm

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

Type this snippet

Step 3 of 4 in Expressions, step 7 of 32 in Polars.

← Previous Next →