5

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

rchitect-of-info
  • 1,150
  • 1
  • 11
  • 23

3 Answers3

4

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   │
└─────┴─────┘

ritchie46
  • 10,405
  • 1
  • 24
  • 43
4

You can use polars.Expr.map_alias, which applies a given function to each column name. It is particularly useful for renaming columns in method chaining.

import polars as pl

df = pl.DataFrame({
    'col.a': [1, 2],
    'col.b': [3, 2]
})

res = df.select(
    pl.all().map_alias(lambda col_name: col_name.replace('.', '_'))
)

Output:

>>> res

shape: (2, 2)
┌───────┬───────┐
│ col_a ┆ col_b │
│ ---   ┆ ---   │
│ i64   ┆ i64   │
╞═══════╪═══════╡
│ 1     ┆ 3     │
│ 2     ┆ 2     │
└───────┴───────┘
Rodalm
  • 5,169
  • 5
  • 21
2

Similar to a pandas df, there is a rename method in polars which replaces column name with a dictionary mapper.

df = df.rename({"old_name": "new_name})

polars docs

abc
  • 43
  • 4
  • This partially answers the question. The ask is to search for a particular character and replace it with another character. Please edit your answer and add the missing part. – Azhar Khan Feb 12 '23 at 03:44