rename
df.rename(columns={"old": "new"}) returns a DataFrame with the listed columns renamed and the others unchanged. Pass a function instead of a dict, columns=str.lower, to transform every name, or assign a full list to df.columns to replace all names at once.
Syntax
df.rename(columns=None, index=None, inplace=False, errors="ignore")| Part | What it is |
|---|---|
columns | Dict of old name to new name, or a function applied to each name |
index | Same, for row labels |
errors | "raise" to error when a key in the dict does not exist |
Examples
import pandas as pd
df = pd.DataFrame({"First Name": ["Ana", "Ben"], "Salary ($)": [50000, 62000]})
df = df.rename(columns={"First Name": "first_name", "Salary ($)": "salary"})
df.columns.tolist()Result: ['first_name', 'salary']
df = pd.DataFrame({"First Name": ["Ana"], "Salary ($)": [50000]})
df.rename(columns=lambda c: c.lower().replace(" ", "_")).columns.tolist()Result: ['first_name', 'salary_($)']
df.columns = ["name", "salary"]
dfResult: name salary 0 Ana 50000
Assigning a list replaces all names; the list length must equal the number of columns.
Common mistakes
- Nothing renamed: rename returns a new frame; assign it back or use inplace=True, and check the old names match exactly (spaces, case).
- ValueError: Length mismatch when assigning df.columns: the list must have exactly one name per column.
- Passing the dict positionally, df.rename({"a": "b"}), renames the index, not the columns; use columns= or axis=1.
Practice rename
These drills check your answer on live data, free, no account needed.
- Rename columns and replace a placeholderRename the columns `Qty` to `qty`, `Unit Price` to `unit_price` and `Region` to `region`. Then replace the text "N/A" in the region column with "Unknown". Return the table.
Questions
How do I rename a single column?
df = df.rename(columns={"old": "new"}). Only that column changes.
How do I remove spaces from all column names?
df.columns = df.columns.str.strip().str.replace(" ", "_").str.lower(). The .str accessor works on the column index.
How do I rename columns while reading a CSV?
pd.read_csv(path, header=0, names=["a", "b", "c"]) replaces the header names with yours.
Related
- set_index and reset_indexHow to use set_index and reset_index in pandas: make a column the row index, go back to a plain column, drop the index, and flatten a groupby result.
- astypeHow to change a column type in pandas with astype and pd.to_numeric: text to numbers, float to int, strings, categories, nullable Int64, bad values and NaN.
- pd.read_csvHow to read a CSV file in pandas with pd.read_csv: separators, headers, index columns, parsing dates, selecting columns, dtypes and the errors people hit.
- mapHow Series.map works in pandas to recode a column with a dict or lookup Series, apply a function per value, what unmatched values become, and map vs replace.