Normalize numeric dtypes
A DataFrame contains numeric columns with inconsistent widths and needs a common representation.
Polars · Module
Converts selected DataFrame columns, or every column, to specified data types. Use mappings or selectors for targeted casts and strict=False to turn invalid conversions into nulls.
DataFrame.cast returns a DataFrame with converted column types. Pass one dtype to convert every column, or provide a mapping whose keys are column names, selectors, or dtypes; strict controls whether invalid conversions raise or become null.
DataFrame.cast(dtypes: Mapping[ColumnNameOrSelector | PolarsDataType, PolarsDataType | PythonDataType] | PolarsDataType | Schema, *, strict: bool = True) → DataFrame| Name | Type | Description |
|---|---|---|
dtypes | Mapping[ColumnNameOrSelector | PolarsDataType, PolarsDataType | PythonDataType] | PolarsDataType | Schema | Mapping of column names or selectors to target dtypes, one dtype for all columns, or a Schema. |
strict | bool = True | Controls invalid conversions; when false, invalid casts produce null values. |
DataFrame
import polars as pl
import polars.selectors as cs
df = pl.DataFrame({
"count": [1, 2, 3],
"price": [6.0, 7.0, 8.0],
"date": ["2020-01-02", "2021-03-04", "2022-05-06"],
})
result = df.cast({cs.numeric(): pl.UInt32, "date": pl.Date})
print(result.dtypes)Casts every numeric column to UInt32 and converts the date strings to Date.
A DataFrame contains numeric columns with inconsistent widths and needs a common representation.
A pipeline must convert all columns to a uniform textual representation.
Input data may contain values that cannot be parsed into the requested type.
DataFrame.cast changes the dtype of DataFrame columns and returns a new DataFrame. A single dtype applies to all columns, while a mapping targets columns or selectors individually.
Follow-up: How would you cast only numeric columns? Use a selector such as cs.numeric() as a mapping key, for example df.cast({cs.numeric(): pl.UInt32}).
The dtypes argument accepts a mapping from column names or selectors to target dtypes, a single target dtype, or a Schema. This lets one call express either targeted or whole-frame conversion.
Follow-up: How can temporal and numeric columns receive different targets? Supply multiple selector keys in one mapping, such as cs.numeric() and cs.temporal().
strict defaults to True. When a conversion is invalid, strict mode raises; setting it to False makes invalid converted values null.
Follow-up: When should strict=False be used? Use it when malformed input should be retained as nulls rather than aborting the cast operation.
polars.DataFrame.with_columnspolars.Expr.castpolars.selectors.numericpolars.selectors.temporal