Pandas Rename Columns: rename() and Replace Values with Examples
Renaming columns is a common data-cleaning task in Pandas. Real datasets may contain spaces, inconsistent capitalisation, abbreviations or labels that are difficult to use in Python code. The DataFrame.rename() method lets you change selected column labels without rewriting the entire column list.
This guide explains how to rename one or more columns, rename every column, standardise labels, replace values in a column, and avoid common mistakes. Examples use practical tabular data and explain when to choose rename(), direct assignment, replace() or string methods.
Related guides: Pandas DataFrames, select rows and columns, missing values, remove duplicates and merge DataFrames.
1. Why rename columns in Pandas?
Clear column names make analysis code easier to read and maintain. For example, Total Sales (£) is understandable to a person, but total_sales_gbp is often easier to use consistently in Python scripts and analytics pipelines.
- Make column labels consistent across files.
- Remove spaces and punctuation from field names.
- Correct spelling or misleading labels.
- Make columns from separate datasets easier to compare before a merge.
- Standardise categories such as
"UK","U.K."and"United Kingdom".
2. Create a sample DataFrame
Suppose a sales file uses inconsistent labels and category values.
import pandas as pd
df = pd.DataFrame({
"Customer Name": ["Aisha", "Bilal", "Chen", "Dina"],
"Sales (£)": [250, 180, 320, 150],
"Region": ["UK", "U.K.", "United Kingdom", "UK"],
"Status": ["active", "Active", "inactive", "active"]
})
print(df)
We can make the column labels consistent, then standardise the values in Region and Status.
3. Pandas rename() syntax
df.rename(mapper=None, *, index=None, columns=None, axis=None, inplace=False, errors="ignore")
| Parameter | Meaning | Example |
|---|---|---|
columns | Dictionary or function used to rename column labels | {"Sales (£)": "sales_gbp"} |
index | Rename index labels | {0: "first"} |
axis | Choose whether labels refer to rows or columns | axis="columns" |
inplace | Modify the existing object rather than return a renamed copy | inplace=True |
errors | Use "raise" to error if a requested label is absent | errors="raise" |
The recommended beginner-friendly form is df.rename(columns={"old_name": "new_name"}). By default, it returns a new DataFrame and leaves the original unchanged.
4. Rename one column
df2 = df.rename(columns={"Customer Name": "customer_name"})
print(df2.columns.tolist())
Only the specified label changes. All other columns remain the same. Assigning the returned DataFrame to df2 keeps the original df intact.
5. Rename multiple columns
Pass a dictionary containing each old label and its new label.
df = df.rename(columns={
"Customer Name": "customer_name",
"Sales (£)": "sales_gbp",
"Region": "region",
"Status": "status"
})
print(df.columns.tolist())
Column labels that are not included in the dictionary remain unchanged. This makes rename() useful when only a few fields need correction in a wide dataset.
6. Rename all columns at once
If every column needs a new name, assign a list to df.columns. The list must have exactly the same number of labels as the DataFrame has columns.
df.columns = ["customer_name", "sales_gbp", "region", "status"]
For a repeatable transformation, you can also use a list comprehension to normalise all names.
df.columns = [column.strip().lower().replace(" ", "_") for column in df.columns]
rename(columns={...}) when you want to change only selected labels.7. Standardise column names automatically
Column names from spreadsheets may contain spaces, uppercase letters or punctuation. A small transformation can make names more consistent.
df.columns = (
df.columns
.str.strip()
.str.lower()
.str.replace(" ", "_", regex=False)
.str.replace(r"[^a-z0-9_]", "", regex=True)
)
This pattern trims leading and trailing spaces, converts labels to lowercase, changes spaces to underscores and removes other characters. Inspect the resulting labels before using this approach, because different original labels can sometimes become identical after cleaning.
Rename columns using a function
df = df.rename(columns=lambda column: column.strip().lower().replace(" ", "_"))
A function is convenient when the same naming rule should be applied to every column.
8. Replace values in a column with replace()
To change values rather than column labels, use Series.replace() or DataFrame.replace(). Here, standardise region names.
df["region"] = df["region"].replace({
"UK": "United Kingdom",
"U.K.": "United Kingdom"
})
The dictionary maps old values to their replacements. Values not listed in the dictionary stay unchanged.
Replace values in several columns
df = df.replace({
"U.K.": "United Kingdom",
"active": "Active",
"inactive": "Inactive"
})
This replaces matching values throughout the DataFrame. If a replacement should apply only to one field, prefer assigning to that column specifically.
Replace a value in only one column
df["status"] = df["status"].replace({
"active": "Active",
"inactive": "Inactive"
})
9. Use map() to standardise category labels
map() is useful when you want to map known values in a single Series to new values.
region_map = {
"UK": "United Kingdom",
"U.K.": "United Kingdom",
"United Kingdom": "United Kingdom"
}
df["region"] = df["region"].map(region_map)
Be aware that dictionary-based map() returns missing values for source values that are not present in the mapping dictionary. Use replace() if you want unlisted values to remain unchanged.
10. Clean text values with string methods
Before replacing labels, remove unwanted spaces and standardise letter case. Pandas string methods are vectorised and operate on each value in a Series.
df["status"] = df["status"].astype("string").str.strip().str.title()
df["region"] = df["region"].astype("string").str.strip()
For example, values such as " active " and "ACTIVE" can be normalised to "Active". After trimming text, use replace() or map() to unify synonymous labels.
11. Rename index labels
The rename() method can rename index labels as well as columns. Use the index argument when row labels need to change.
df2 = df.rename(index={0: "row_one", 1: "row_two"})
To rename the index axis label itself, use df.index.name = "record_id". This does not change the values in the index.
12. Common mistakes and how to fix them
| Problem | Why it happens | Solution |
|---|---|---|
| Column name does not change | The old label may contain spaces or different capitalisation. | Check df.columns.tolist() and copy the exact label. |
| Original DataFrame remains unchanged | rename() returns a new DataFrame by default. | Assign the result: df = df.rename(...). |
| Length mismatch when assigning columns | The list length differs from the number of columns. | Check df.shape[1] before assigning names. |
Unexpected missing values after map() | A source value is not present in the mapping dictionary. | Use replace() when unlisted values should stay unchanged. |
| Two labels become identical | Normalisation can make different names look the same. | Inspect df.columns.duplicated() after cleaning. |
| Values in an unrelated column change | DataFrame.replace() applies across the DataFrame. | Use df["column"] = df["column"].replace(...). |
13. Practice exercises with solutions
Exercise 1: Rename a single column
Rename "Customer Name" to "customer_name".
Show solution
df = df.rename(columns={"Customer Name": "customer_name"})
Exercise 2: Rename multiple columns
Rename "Sales (£)" to "sales_gbp" and "Region" to "region".
Show solution
df = df.rename(columns={"Sales (£)": "sales_gbp", "Region": "region"})
Exercise 3: Replace region values
Replace "UK" and "U.K." with "United Kingdom" in the region column.
Show solution
df["region"] = df["region"].replace({"UK": "United Kingdom", "U.K.": "United Kingdom"})
Exercise 4: Standardise all column labels
Convert all column names to lowercase and replace spaces with underscores.
Show solution
df.columns = [c.strip().lower().replace(" ", "_") for c in df.columns]
Exercise 5: Standardise category capitalisation
Trim extra spaces and convert values in status to title case.
Show solution
df["status"] = df["status"].astype("string").str.strip().str.title()
14. Frequently asked questions
How do I rename a column in Pandas?
Use df.rename(columns={"old_name": "new_name"}) and assign the result back to a variable if you want to keep the change.
How do I rename multiple columns?
Pass a dictionary with each old column name as a key and its new name as the value.
How do I rename all columns at once?
Assign a list of new names to df.columns. The list must contain exactly one name for each column.
What is the difference between rename() and replace()?
rename() changes labels such as column names or index labels. replace() changes matching data values inside a Series or DataFrame.
What is the difference between replace() and map()?
For dictionary mappings, replace() leaves unlisted values unchanged, while map() generally produces missing values for keys absent from the mapping.
How can I check column names after renaming?
Use df.columns.tolist() to inspect the current column labels.
