Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,...

like image 661
Dante Avatar asked Dec 08 '25 08:12

Dante


1 Answers

df = df.with_columns(
    pl.col("asset_number").fill_null(
        "PREFIX - " + pl.int_range(pl.len()).cast(pl.String)
    )
)
like image 123
BallpointBen Avatar answered Dec 12 '25 12:12

BallpointBen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!