Convert text to numbers
A column contains numeric text that must participate in arithmetic or numeric filtering.
Polars · Module
Expr.cast converts an expression to a specified data type. Failed casts raise by default, or become null with strict=False; numeric overflow can be wrapped explicitly.
Expr.cast changes the data type of an expression while keeping the operation inside Polars' expression pipeline. By default, invalid conversions raise an exception; setting strict=False turns invalid results into nulls, while wrap_numerical=True permits overflowing numeric casts to wrap.
Expr.cast(dtype: PolarsDataType | DataTypeExpr | type[Any], *, strict: bool = True, wrap_numerical: bool = False) → Expr| Name | Type | Description |
|---|---|---|
dtype | PolarsDataType | DataTypeExpr | type[Any] | Data type to cast to. |
strict | bool = True | Raise if cast is invalid; when false, invalid casts produce null values. |
wrap_numerical | bool = False | Wrap overflowing numeric casts instead of marking them as invalid. |
Expr
strict=False, values that cannot be converted do not raise an exception; Polars produces null values instead.wrap_numerical=True changes overflow handling from invalid-cast behavior to wrapping.import polars as pl
df = pl.DataFrame({"a": [1, 2, 3], "b": ["4", "5", "6"]})
result = df.with_columns(
pl.col("a").cast(pl.Float64),
pl.col("b").cast(pl.Int32),
)
print(result)Casts two expression columns to different target data types.
A column contains numeric text that must participate in arithmetic or numeric filtering.
A pipeline needs consistent numeric precision or integer width across expressions.
Input data may contain malformed values that should become missing values instead of stopping processing.
Expr.cast do?Expr.cast converts an expression to a requested data type and returns another expression. The target may be a Polars data type, a data-type expression, or a Python type.
Follow-up: How would you preserve a lazy expression pipeline while converting a string column? Use pl.col("name").cast(pl.Int32) inside select or with_columns.
The default is strict=True, so an invalid conversion raises an exception. With strict=False, invalid casts produce null values instead.
Follow-up: When is non-strict casting useful? It is useful when malformed input should be retained in the result as missing data rather than aborting the operation.
wrap_numerical?wrap_numerical controls overflow behavior for numeric casts. When enabled, overflowing numeric values wrap instead of being marked as invalid.
Follow-up: What should be considered before enabling it? Verify that wraparound semantics are acceptable, because the resulting value may differ substantially from the original.
polars.Series.castpolars.DataFrame.castpolars.colpolars.Expr