pythondataframedata-sciencedata-cleaningpython-polars

How can I replace null values in polars with a prefix with ascending numbers?


I am trying to replace null values in my dataframe column by a prefix and ascending numbers(to make each unique).ie

df = pl.from_repr("""
┌──────────────┬──────────────┐
│ name         ┆ asset_number │
│ ---          ┆ ---          │
│ str          ┆ str          │
╞══════════════╪══════════════╡
│ Office Chair ┆ null         │
│ Office Chair ┆ null         │
│ Office Chair ┆ null         │
│ Office Chair ┆ CMP - 001    │
│ Office Chair ┆ CMP - 005    │
│ Office Chair ┆ null         │
│ Table        ┆ null         │
│ Table        ┆ CMP - 007    │
└──────────────┴──────────────┘
""")

the null values should be replaced to something like PREFIX - 001,PREFIX - 002,...


Solution

  • df = df.with_columns(
        pl.col("asset_number").fill_null(
            "PREFIX - " + pl.int_range(pl.len()).cast(pl.String)
        )
    )