How to replace string values in a strict way in Polars?
16:44 09 May 2025

I'm working with a Polars DataFrame that contains a column with string values. I aim to replace specific values in this column using the str.replace_many() method.

My dataframe:

import polars as pl
df = (pl.DataFrame({"Products": ["cell_foo","cell_fooFlex","cell_fooPro"]}))

Current approach:

mapping= {
    "cell_foo" : "cell",
    "cell_fooFlex" : "cell",
    "cell_fooPro": "cell"
}

(df.with_columns(pl.col("Products").str.replace_many(mapping ).alias("Replaced")))

Output:

shape: (3, 2)
┌──────────────┬──────────┐
│ Products     ┆ Replaced │
│ ---          ┆ ---      │
│ str          ┆ str      │
╞══════════════╪══════════╡
│ cell_foo     ┆ cell     │
│ cell_fooFlex ┆ cellFlex │
│ cell_fooPro  ┆ cellPro  │
└──────────────┴──────────┘

Desired Output:

shape: (3, 2)
┌──────────────┬──────────┐
│ Products     ┆ Replaced │
│ ---          ┆ ---      │
│ str          ┆ str      │
╞══════════════╪══════════╡
│ cell_foo     ┆ cell     │
│ cell_fooFlex ┆ cell     │
│ cell_fooPro  ┆ cell     │
└──────────────┴──────────┘

How can I modify my approach to ensure that replacements occur only when the entire string matches a key in the mapping?

python dataframe python-polars