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
castraises on overflow unlessstrict=False.schemareports every column's type at once.Categoricalstores repeated strings once.
Keywords and builtins used here
asprint
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.
Step 4 of 4 in Series & frames, step 4 of 32 in Polars.