Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename all columns in dataframe to lowercase

Given a polars dataframe I want to rename all columns to their lowercase version. As per polars.Expr.name.to_lowercase we can do

import polars as pl
pl.DataFrame([{'CCY': 'EUR', 'Qty': 123},
              {'CCY': 'USD', 'Qty': 456}]).with_columns(pl.all().name.to_lowercase())

but this duplicates the data (as it keeps the original column names).

Conceptually, I am looking for something like

pl.DataFrame(...).rename({c: c.name.to_lowercase() for c in pl.all()})

But this doesn't work since pl.all() is not iterable.

like image 566
Phil-ZXX Avatar asked Oct 31 '25 11:10

Phil-ZXX


1 Answers

select rather than with_columns:

df.select(pl.all().name.to_lowercase())

Output:

┌─────┬─────┐
│ ccy ┆ qty │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ EUR ┆ 123 │
│ USD ┆ 456 │
└─────┴─────┘

Note that you could also use your envisioned approach with cs.expand_selector:

import polars.selectors as cs

df.rename({c: c.lower() for c in cs.expand_selector(df, cs.all())})

although in the case of all columns could be replaced by a simple:

df.rename(str.lower)
like image 199
mozway Avatar answered Nov 03 '25 01:11

mozway