Search code examples
python-polars

Polars: Search and replace in column names


This used to be handled in pandas as so:

df.columns = df.columns.str.replace('.','_')

This code works but definitely doesn't feel like the correct solution.

renamed = {}
for column_name in list(filter(lambda x: '.' in  x, df.columns)):
    renamed[column_name] = column_name.replace('.', '_')
df = df.rename(renamed)

Thx


Solution

  • df.columns returns a python List[str] and it also supports __setitem__, so you can just use python here.

    df = pl.DataFrame({
        "a.c": [1, 2],
        "b.d": [3, 4]
    })
    df.columns = list(map(lambda x: x.replace(".", "_"), df.columns))
    print(df)
    
    shape: (2, 2)
    ┌─────┬─────┐
    │ a_c ┆ b_d │
    │ --- ┆ --- │
    │ i64 ┆ i64 │
    ╞═════╪═════╡
    │ 1   ┆ 3   │
    ├╌╌╌╌╌┼╌╌╌╌╌┤
    │ 2   ┆ 4   │
    └─────┴─────┘