Renaming columns is one of the first things you do after loading messy data. Polars keeps it simple, and nothing mutates in place: every rename returns a new frame. Here is each clean way to do it.
Rename one column or several at once
The main tool is df.rename, which takes a dict that maps old names to new ones. One pair or many, it works the same.
- df = df.rename({"old": "new"})
- df = df.rename({"a": "alpha", "b": "beta"})
- # only the columns you name change; the rest stay as they are
Replace column names with a dict
If you already have a mapping dict, hand it straight to rename. This is the answer to replacing column names from a dictionary.
- mapping = {"col1": "id", "col2": "date", "col3": "amount"}
- df = df.rename(mapping)
Rename every column with a function
To transform all the names at once, build the dict from df.columns with a comprehension. This covers lowercasing, trimming, and swapping spaces for underscores.
- # lowercase every column name:
- df = df.rename({c: c.lower() for c in df.columns})
- # strip spaces and use snake_case:
- df = df.rename({c: c.strip().lower().replace(" ", "_") for c in df.columns})
Rename inline with alias
When you are already selecting or transforming, rename in the same step with .alias instead of a separate rename call. This is the idiomatic Polars style inside select and with_columns.
- df.select(pl.col("old").alias("new"))
- df.with_columns((pl.col("price") * 1.2).alias("price_with_tax"))
Everything here works the same on a LazyFrame. Renaming only relabels, so it is cheap: use it freely early in a lazy pipeline before you collect. For the full toolkit, see the Python Polars cheat sheet. Next up: creating DataFrames and filtering rows.
This post was originally published on my site. Read the full article and more →
Top comments (0)