I want to change the column labels of a Polars DataFrame from
['#a', '#b', '#c', '#d']
to
['a', 'b', 'c', 'd']
The following approach is most effective when renaming all columns that follow a consistent pattern, such as a common prefix or suffix.
df.columns = [col.lstrip("#") for col in df.columns]
Alternatively, the approach outlined below is most suitable when renaming specific columns or when no consistent pattern is present:
df = df.rename({
"#a": "a",
"#b": "b",
"#c": "c",
"#d": "d"
})
Output:
┌─────┬─────┬─────┬─────┐
│ a ┆ b ┆ c ┆ d │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ 1 ┆ 3 ┆ 5 ┆ 7 │
│ 2 ┆ 4 ┆ 6 ┆ 8 │
└─────┴─────┴─────┴─────┘