How to Rename Columns in pandas (df.rename and 6 Other Ways)
To rename a column in pandas, use df = df.rename(columns={"old_name": "new_name"}). Put as many "old": "new" pairs in the dictionary as you like; columns you don't mention keep their names. To replace every column name at once, assign a list of the same length: df.columns = ["a", "b", "c"].
Those two cover most cases. The rest of this guide shows the other options (functions, string methods, set_axis, prefixes, MultiIndex columns, the row index) and the mistakes that trip people up, especially the one where a typo in the old name is silently ignored. Every snippet was run with pandas 2.3 and pandas 3.1.
The examples use this DataFrame:
import pandas as pd
df = pd.DataFrame({
"First Name": ["Ada", "Alan"],
"Last Name": ["Lovelace", "Turing"],
"DOB": ["1815-12-10", "1912-06-23"],
})Rename specific columns with df.rename
df = df.rename(columns={"First Name": "first_name", "DOB": "birth_date"})
print(df.columns.tolist())
# ['first_name', 'Last Name', 'birth_date']rename returns a new DataFrame, so assign the result back (to df or to a new variable). This is the safest way to rename because it is explicit about which name maps to which, and the column order never matters.
You can also pass the mapping positionally with an axis, which reads well in method chains:
df.rename({"DOB": "dob"}, axis="columns") # same as axis=1Rename a column by position
rename works on names, but you can look the name up by position first:
df = df.rename(columns={df.columns[2]: "birth_date"})inplace=True vs reassigning
Older tutorials write df.rename(columns={...}, inplace=True). That modifies df and returns None, which leads to a classic bug:
df = df.rename(columns={"DOB": "dob"}, inplace=True)
print(df) # NonePrefer reassigning. As of pandas 3.1 (released October 2026), the inplace keyword of rename and rename_axis is deprecated and emits a Pandas4Warning; it gave no performance benefit over reassigning. Reassigning works in every version and lets you chain calls:
clean = (
pd.read_csv("people.csv")
.rename(columns={"DOB": "birth_date"})
.dropna()
)Replace all column names: df.columns = [...]
When you want to set every name, assign a list or other sequence to df.columns:
df.columns = ["first_name", "last_name", "birth_date"]The list must have exactly as many items as there are columns, in the current order. Otherwise you get:
ValueError: Length mismatch: Expected axis has 3 elements, new values have 2 elementsThis is fast and concise, but fragile: if the source file gains or reorders a column, the names silently land on the wrong data. Use rename with a dictionary for anything you load from outside.
set_axis for method chains
set_axis does the same as assigning df.columns, but returns a new DataFrame:
df = df.set_axis(["first_name", "last_name", "birth_date"], axis=1)Rename columns with a function
rename(columns=...) also accepts any function, which is applied to every column name:
df.rename(columns=str.lower)
# ['first name', 'last name', 'dob']
df.rename(columns=lambda c: c.strip().lower().replace(" ", "_"))
# ['first_name', 'last_name', 'dob']Clean all names with .str methods
df.columns is an Index, and it has the same .str accessor as a string Series. This is the usual way to normalise messy headers from a spreadsheet or CSV export into snake_case:
df.columns = (
df.columns
.str.strip()
.str.lower()
.str.replace(" ", "_")
)
# ['first_name', 'last_name', 'dob']For headers with punctuation, replace any run of non-alphanumeric characters with a regular expression. Since pandas 2.0, str.replace treats the pattern literally unless you pass regex=True:
df.columns = df.columns.str.replace(r"[^0-9a-zA-Z]+", "_", regex=True).str.lower()Clean, predictable column names follow the same rules as good file names: lowercase, no spaces, one separator. Our guide to naming conventions covers snake_case and friends in more detail.
Add a prefix or suffix
df.add_prefix("emp_") # ['emp_First Name', 'emp_Last Name', 'emp_DOB']
df.add_suffix("_raw") # ['First Name_raw', 'Last Name_raw', 'DOB_raw']This is handy before a merge, so that columns from two sources don't collide. On a DataFrame these change the column labels; on a Series they change the row labels.
Rename MultiIndex columns
With hierarchical columns, a mapping in rename is applied to every level:
mi = pd.DataFrame(
[[1, 2, 3, 4]],
columns=pd.MultiIndex.from_tuples(
[("sales", "q1"), ("sales", "q2"), ("cost", "q1"), ("cost", "q2")]
),
)
mi.rename(columns={"sales": "revenue"}, level=0)
# [('revenue', 'q1'), ('revenue', 'q2'), ('cost', 'q1'), ('cost', 'q2')]Pass level= to restrict the change to one level, which matters when the same label appears at several levels. To flatten a MultiIndex into single strings (often what you want before writing to CSV):
mi.columns = ["_".join(col) for col in mi.columns]
# ['sales_q1', 'sales_q2', 'cost_q1', 'cost_q2']After a groupby, you can skip the renaming step entirely with named aggregation, which sets the output names directly:
totals = sales.groupby("region").agg(total=("amount", "sum"), orders=("amount", "count"))Rename the index (row labels)
The same method renames row labels with index=:
people = df.set_index("Last Name")
people = people.rename(index={"Turing": "TURING"})To rename the index itself (the label shown above the row names), or the name of the columns axis, use rename_axis:
people = people.rename_axis("surname") # index name
people = people.rename_axis(columns="field") # columns axis nameA Series has a single name rather than columns; change it with s.rename("new_name").
Common errors
A typo in the old name does nothing
This is the big one. By default, rename ignores keys that don't match a column, so this runs without complaint and changes nothing:
df.rename(columns={"Frist Name": "first_name"}) # no error, no changeAdd errors="raise" to make pandas tell you:
df.rename(columns={"Frist Name": "first_name"}, errors="raise")
# KeyError: "['Frist Name'] not found in axis"It is worth using in any pipeline that reads files you don't control. Hidden whitespace is the usual culprit: "DOB " with a trailing space doesn't match "DOB". Print df.columns.tolist() to see the exact names, and .str.strip() them first.
Duplicate names after a rename
pandas allows duplicate column names, so mapping two columns to the same name, or using set_axis with a repeated label, also succeeds silently. Afterwards df["name"] returns a DataFrame instead of a Series. Check with df.columns.is_unique.
Editing df.columns.values
Assigning into df.columns.values[0] worked by accident in older versions. In pandas 3.1 it raises ValueError: Cannot modify read-only array for string column names. Use rename or assign a whole new list.
Forgetting to assign the result
df.rename(columns={...}) on its own line does nothing visible: it returns a renamed copy that is thrown away. Write df = df.rename(...).
Quick reference
| Goal | Code |
|---|---|
| Rename one or a few columns | df = df.rename(columns={"old": "new"}) |
| Fail loudly on a typo | df.rename(columns={...}, errors="raise") |
| Replace all names | df.columns = [...] or df.set_axis([...], axis=1) |
| Apply a function to every name | df.rename(columns=str.lower) |
| snake_case all headers | df.columns.str.strip().str.lower().str.replace(" ", "_") |
| Prefix or suffix | df.add_prefix("x_"), df.add_suffix("_y") |
| One level of a MultiIndex | df.rename(columns={...}, level=0) |
| Row labels / index name | df.rename(index={...}), df.rename_axis("name") |
Renaming the files that hold your data is a different task. To rename CSVs and spreadsheets on disk from Python, see rename files with Python. If you have a folder of exports with meaningless names like export (7).csv, File Renamer AI can read each file and suggest a descriptive name, and our file naming conventions guide helps you pick a pattern.
Frequently Asked Questions
How do I rename a single column in pandas?
Use df = df.rename(columns={"old_name": "new_name"}). Only the column you name changes; all other columns keep their names and order. Add errors="raise" if you want an error when the old name doesn't exist.
How do I rename all columns in a pandas DataFrame?
Assign a list with one name per column, in order: df.columns = ["a", "b", "c"]. For a method-chain-friendly version, use df.set_axis(["a", "b", "c"], axis=1). To transform every existing name, pass a function instead, for example df.rename(columns=str.lower).
Why is df.rename not changing my column names?
Usually one of two reasons. Either the result was not assigned back (write df = df.rename(...)), or the old name doesn't exactly match a column, often because of a trailing space or different capitalisation. rename ignores unknown keys by default, so pass errors="raise" to see the problem.
Should I use inplace=True with rename?
No. inplace=True returns None, which causes bugs when people write df = df.rename(..., inplace=True), and it gives no performance benefit. pandas 3.1 deprecated the inplace keyword for rename and rename_axis, so reassigning the result is the forward-compatible style.
How do I make all column names lowercase with underscores?
Use the string methods on the column index: df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_"). For headers with punctuation, use df.columns.str.replace(r"[^0-9a-zA-Z]+", "_", regex=True) before lowercasing.
How do I rename the index in pandas?
Use df.rename(index={"old_label": "new_label"}) to change individual row labels, and df.rename_axis("new_name") to change the name of the index itself. For a Series, s.rename("new_name") changes the Series name.
Related Posts
How to Rename Columns in R (dplyr, Base R and data.table)
Rename columns in R with dplyr::rename(new = old), rename_with for patterns, base R names() and colnames(), or data.table setnames. Examples for every case.
AdvancedHow to Rename a GitHub Repository (and What Breaks)
Rename a GitHub repository in Settings > General, then update your local remote with git remote set-url. What redirects, and what breaks: Pages and Actions.
GuideHow to Rename a Column in Google Sheets (What Actually Works)
Google Sheets column letters can't be renamed, but you can name columns with a header row, a named range or a table. Step-by-step for each, plus freezing.
Ready to organize your files?
Try AI renaming right away. No sign-up needed until you download.
Try It Free