Reputation: 3275
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.
Upvotes: 3
Views: 191
Reputation: 262214
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)
Upvotes: 4
Reputation: 117540
As said already, you can use select()
instead of with_columns()
. You can also use pl.DataFrame.rename()
with function instead of dictionary:
pl.DataFrame([
{'CCY': 'EUR', 'Qty': 123},
{'CCY': 'USD', 'Qty': 456}
]).rename(str.lower)
shape: (2, 2)
┌─────┬─────┐
│ ccy ┆ qty │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ EUR ┆ 123 │
│ USD ┆ 456 │
└─────┴─────┘
You can also use pl.DataFrame.columns
to get columns list, if you want to create dictionary:
df = pl.DataFrame([
{'CCY': 'EUR', 'Qty': 123},
{'CCY': 'USD', 'Qty': 456}
])
df.rename({c: c.lower() for c in df.columns})
shape: (2, 2)
┌─────┬─────┐
│ ccy ┆ qty │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ EUR ┆ 123 │
│ USD ┆ 456 │
└─────┴─────┘
Upvotes: 2
Reputation: 14369
Using df.rename
+ built-in str.lower
:
df.rename(lambda col_name: col_name.lower())
Output:
shape: (2, 2)
┌─────┬─────┐
│ ccy ┆ qty │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ EUR ┆ 123 │
│ USD ┆ 456 │
└─────┴─────┘
Upvotes: 3