Targeted schema cleanup
Rename a small, known set of columns after reading data with external or legacy names.
Polars · Module
Rename DataFrame columns with an explicit old-to-new mapping or a function that derives new names. By default, Polars validates that mapped source names exist.
Call rename on a DataFrame with either a mapping of existing column names to replacement names or a function that transforms each column name. The operation returns a DataFrame with the resulting schema; strict validation is enabled by default.
DataFrame.rename(mapping: Mapping[str, str] | Callable[[str], str], *, strict: bool = True) → DataFrame| Name | Type | Description |
|---|---|---|
mapping | Mapping[str, str] | Callable[[str], str] | Mapping from old column names to new names, or a callable that accepts an old name and returns its replacement. |
strict | bool = True | Whether to validate that all referenced column names exist in the current schema. |
DataFrame
import polars as pl
df = pl.DataFrame({"foo": [1, 2], "bar": [3, 4]})
renamed = df.rename({"foo": "apple"})
print(renamed)Creates a new DataFrame with the selected column renamed.
Rename a small, known set of columns after reading data with external or legacy names.
Apply a consistent prefix, suffix, or transformation to every column name.
Handle optional input columns without raising when some mapped names are absent.
It accepts either a mapping from old names to new names or a callable that receives each old column name and returns its replacement. It returns a DataFrame with renamed columns.
Follow-up: How would you rename every column using one rule? Pass a callable, such as lambda name: "c_" + name.
strict defaults to True and validates that all names referenced by the mapping are present in the DataFrame schema. If a referenced name is absent, the operation raises an exception.
Follow-up: How can a caller avoid failure for a mapping that may contain absent names? Set strict=False.
A dictionary mapping is useful for selected renames, while a callable applies a naming rule to column names. Both approaches produce a DataFrame with the updated column names.
Follow-up: How can you transform names without specifying them individually? Use a callable that derives each new name from the old one.
DataFrame.selectDataFrame.with_columnsDataFrame.columns