Search code examples
pythonpython-3.xdataframepython-polars

All columns to uppercase in a DataFrame?


Suppose there are hundreds of columns in a DataFrame. Some of the column names are in lower and some are in upper case.

Now, I want to convert all the columns to upper case.

import polars as pl

df = pl.DataFrame({
    "foo": [1, 2, 3, 4, 5, 8],
    "baz": [5, 4, 3, 2, 1, 9],
    
})

What I tried:

df.columns = [x.upper() for x in df.columns]

It worked, but is there any other way preferably without a for loop?


Solution

  • .rename() also accepts a Callable.

    df.rename(str.upper)
    
    shape: (6, 2)
    ┌─────┬─────┐
    │ FOO ┆ BAZ │
    │ --- ┆ --- │
    │ i64 ┆ i64 │
    ╞═════╪═════╡
    │ 1   ┆ 5   │
    │ 2   ┆ 4   │
    │ 3   ┆ 3   │
    │ 4   ┆ 2   │
    │ 5   ┆ 1   │
    │ 8   ┆ 9   │
    └─────┴─────┘