pythonstringreplacepython-polars

Polars - Replace part of string in column with value of other column


So I have a Polars dataframe looking as such

df = pl.DataFrame(
    {
        "ItemId": [15148, 15148, 24957],
        "SuffixFactor": [19200, 200, 24],
        "ItemRand": [254, -1, -44],
        "Stat0": ['+5 Defense', '+$i Might', '+9 Vitality'],
        "Amount": ['', '7', '']
    }
)

I want to replace $i in the column "Stat0" with Amount whenever Stat0 contains i$

I have tried a couple different things such as:

df = df.with_columns(
    pl.col('Stat0').str.replace(r'\$i', pl.col('Amount'))
)

Expected result

result = pl.DataFrame(
    {
        "ItemId": [15148, 15148, 24957],
        "SuffixFactor": [19200, 200, 24],
        "ItemRand": [254, -1, -44],
        "Stat0": ['+5 Defense', '+7 Might', '+9 Vitality'],
        "Amount": ['', '7', '']
    }
)
shape: (3, 5)
┌────────┬──────────────┬──────────┬─────────────┬────────┐
│ ItemId ┆ SuffixFactor ┆ ItemRand ┆ Stat0       ┆ Amount │
│ ---    ┆ ---          ┆ ---      ┆ ---         ┆ ---    │
│ i64    ┆ i64          ┆ i64      ┆ str         ┆ str    │
╞════════╪══════════════╪══════════╪═════════════╪════════╡
│ 15148  ┆ 19200        ┆ 254      ┆ +5 Defense  ┆        │
│ 15148  ┆ 200          ┆ -1       ┆ +7 Might    ┆ 7      │
│ 24957  ┆ 24           ┆ -44      ┆ +9 Vitality ┆        │
└────────┴──────────────┴──────────┴─────────────┴────────┘

But this doesn't seem to work.

I hope someone can help.

Best regards


Solution

  • As of Polars 0.14.4, the replace and replace_all expressions allow an Expression for the value parameter. Thus, we can solve this more simply as:

    df.with_columns(
        pl.col('Stat0').str.replace(r'\$i', pl.col('Amount'))
    )
    
    shape: (3, 5)
    ┌────────┬──────────────┬──────────┬─────────────┬────────┐
    │ ItemId ┆ SuffixFactor ┆ ItemRand ┆ Stat0       ┆ Amount │
    │ ---    ┆ ---          ┆ ---      ┆ ---         ┆ ---    │
    │ i64    ┆ i64          ┆ i64      ┆ str         ┆ str    │
    ╞════════╪══════════════╪══════════╪═════════════╪════════╡
    │ 15148  ┆ 19200        ┆ 254      ┆ +5 Defense  ┆        │
    │ 15148  ┆ 200          ┆ -1       ┆ +7 Might    ┆ 7      │
    │ 24957  ┆ 24           ┆ -44      ┆ +9 Vitality ┆        │
    └────────┴──────────────┴──────────┴─────────────┴────────┘