pythonlazy-evaluationpython-polars

Polars: Search and replace in column names: is it possible with LazyFrames?


A follow up from an already answered question, is it possible to Search and replace column names in a LazyFrame? I am doing this as a workaround (based on the linked answer by ritchie46, and thanks for that!):

df = df.lazy().collect()
df.columns = list(map(lambda x: x.replace("Total", ""), df.columns)) 

Solution

  • There is also pl.LazyFrame.rename.

    import polars as pl
    
    df = pl.LazyFrame({
        "Total_foo": [1],
        "bar_Total": [2],
        "other": [3],
    })
    
    df.rename(lambda name: name.replace("Total", "")).collect()
    
    shape: (1, 3)
    ┌──────┬──────┬───────┐
    │ _foo ┆ bar_ ┆ other │
    │ ---  ┆ ---  ┆ ---   │
    │ i64  ┆ i64  ┆ i64   │
    ╞══════╪══════╪═══════╡
    │ 1    ┆ 2    ┆ 3     │
    └──────┴──────┴───────┘