typestar

Types and casting in Python

Polars types are explicit: cast deliberately, and strict by default.

import polars as pl

frame = pl.DataFrame({
    "n": ["1", "2", "oops"],
    "kind": ["snippet", "example", "snippet"],
})

cleaned = frame.with_columns(
    pl.col("n").cast(pl.Int64, strict=False),
    pl.col("kind").cast(pl.Categorical),
)
print(cleaned.schema)
print(cleaned)
print(cleaned["n"].null_count(), cleaned.estimated_size("b") > 0)

How it works

  1. cast raises on overflow unless strict=False.
  2. schema reports every column's type at once.
  3. Categorical stores repeated strings once.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
329
Tokens
126
Three-star pace
100 tpm

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

Type this snippet

Step 4 of 4 in Series & frames, step 4 of 32 in Polars.

← Previous Next →