polars.Series.replace#
- Series.replace(
- mapping: dict[Any, Any],
- *,
- default: Any = _NoDefault.no_default,
- return_dtype: PolarsDataType | None = None,
Replace values according to the given mapping.
Needs a global string cache for lazily evaluated queries on columns of type
Categorical
.- Parameters:
- mapping
Mapping of values to their replacement.
- default
Value to use when the mapping does not contain the lookup value. Defaults to keeping the original value.
- return_dtype
Set return dtype to override automatic return dtype determination.
See also
Examples
Replace a single value by another value. Values not in the mapping remain unchanged.
>>> s = pl.Series("a", [1, 2, 2, 3]) >>> s.replace({2: 100}) shape: (4,) Series: 'a' [i64] [ 1 100 100 3 ]
Replace multiple values. Specify a default to set values not in the given map to the default value.
>>> s = pl.Series("country_code", ["FR", "ES", "DE", None]) >>> country_code_map = { ... "CA": "Canada", ... "DE": "Germany", ... "FR": "France", ... None: "unspecified", ... } >>> s.replace(country_code_map, default=None) shape: (4,) Series: 'country_code' [str] [ "France" null "Germany" "unspecified" ]
The return type can be overridden with the
return_dtype
argument.>>> s = pl.Series("a", [0, 1, 2, 3]) >>> s.replace({1: 10, 2: 20}, default=0, return_dtype=pl.UInt8) shape: (4,) Series: 'a' [u8] [ 0 10 20 0 ]