polars.Series.map_dict#

Series.map_dict(
remapping: dict[Any, Any],
*,
default: Any = None,
return_dtype: PolarsDataType | None = None,
) Self[source]#

Replace values in the Series using a remapping dictionary.

Parameters:
remapping

Dictionary containing the before/after values to map.

default

Value to use when the remapping dict does not contain the lookup value. Use pl.first(), to keep the original value.

return_dtype

Set return dtype to override automatic return dtype determination.

Examples

>>> s = pl.Series("iso3166", ["TUR", "???", "JPN", "NLD"])
>>> country_lookup = {
...     "JPN": "Japan",
...     "TUR": "Türkiye",
...     "NLD": "Netherlands",
... }

Remap, setting a default for unrecognised values…

>>> s.map_dict(country_lookup, default="Unspecified").alias("country_name")
shape: (4,)
Series: 'country_name' [str]
[
    "Türkiye"
    "Unspecified"
    "Japan"
    "Netherlands"
]

…or keep the original value, by making use of pl.first():

>>> s.map_dict(country_lookup, default=pl.first()).alias("country_name")
shape: (4,)
Series: 'country_name' [str]
[
    "Türkiye"
    "???"
    "Japan"
    "Netherlands"
]

…or keep the original value, by assigning the input series:

>>> s.map_dict(country_lookup, default=s).alias("country_name")
shape: (4,)
Series: 'country_name' [str]
[
    "Türkiye"
    "???"
    "Japan"
    "Netherlands"
]

Override return dtype:

>>> s = pl.Series("int8", [5, 2, 3], dtype=pl.Int8)
>>> s.map_dict({2: 7}, default=pl.first(), return_dtype=pl.Int16)
shape: (3,)
Series: 'int8' [i16]
[
    5
    7
    3
]