In this Pandas tutorial, you will learn how to change column names in a DataFrame. You can replace every column name, rename selected columns, modify names with a function, and rename columns without changing the original DataFrame.
Change Column Names in a Pandas DataFrame
Pandas provides several ways to rename DataFrame columns. The appropriate method depends on whether you need to replace all column labels or only selected labels.
- Assign a sequence to
DataFrame.columnsto replace every column name. - Use
DataFrame.rename()to rename one or more selected columns. - Pass a function to
rename()to transform all column names using the same rule. - Use
set_axis()when you want to assign a complete set of labels and optionally return a new DataFrame.
| Renaming requirement | Recommended Pandas approach |
|---|---|
| Replace every column name | df.columns = [...] |
| Rename selected columns | df.rename(columns={...}) |
| Apply one rule to every column name | df.rename(columns=function) |
| Keep the original DataFrame unchanged | Assign the result of rename() or set_axis() |
Replace All Pandas DataFrame Column Names with DataFrame.columns
You can access the column labels of a Pandas DataFrame through the DataFrame.columns property. Assign a list or another sequence of labels to this property to replace all existing column names.
Important: The number of new column names must equal the number of columns in the DataFrame. This approach changes the existing DataFrame.
df.columns = ['column_1', 'column_2', 'column_3']
Example 1 – Assign New Names to Every DataFrame Column
In the following example, the DataFrame initially has the column names a, b, and c. Assigning a new list to df.columns changes them to d, e, and f.
Python Example
import pandas as pd
#initialize a dataframe
df = pd.DataFrame({
'a':[14, 52, 46],
'b':[32, 85, 64],
'c':[88, 47, 36]})
#change column names
df.columns = ['d', 'e', 'f']
#print the dataframe
print(df)
Output
d e f
0 14 32 88
1 52 85 47
2 46 64 36
The values and row index remain unchanged. Only the three column labels are replaced.
Example 2 – Length Mismatch While Replacing DataFrame Column Names
In this example, the DataFrame contains three columns, but four new names are assigned to df.columns. Pandas cannot determine which label belongs to which column, so it raises a ValueError.
Python Example
import pandas as pd
#initialize a dataframe
df = pd.DataFrame({
'a':[14, 52, 46],
'b':[32, 85, 64],
'c':[88, 47, 36]})
#change column names
df.columns = ['d', 'e', 'f', 'g']
#print the dataframe
print(df)
Output
ValueError: Length mismatch: Expected axis has 3 elements, new values have 4 elements
The error reports that the existing axis has three labels while the replacement sequence contains four values. Check the number of columns before assigning the new names.
print(len(df.columns))
print(df.columns.tolist())
Output
3
['a', 'b', 'c']
Rename Selected Pandas DataFrame Columns with rename()
Use DataFrame.rename() when only certain column names need to change. Pass a dictionary to the columns argument, where each key is an existing name and each value is its replacement.
new_df = df.rename(columns={
'old_name': 'new_name'
})
By default, rename() returns a new DataFrame and leaves the original DataFrame unchanged.
import pandas as pd
df = pd.DataFrame({
'name': ['Ava', 'Noah'],
'score': [86, 91],
'city': ['Boston', 'Denver']
})
renamed_df = df.rename(columns={
'name': 'student_name',
'score': 'exam_score'
})
print(renamed_df)
Output
student_name exam_score city
0 Ava 86 Boston
1 Noah 91 Denver
The city column is not included in the mapping, so its name remains unchanged.
Change Selected Column Names in the Existing DataFrame
To modify the same DataFrame object, pass inplace=True.
df.rename(
columns={'score': 'exam_score'},
inplace=True
)
print(df.columns.tolist())
Output
['name', 'exam_score', 'city']
When inplace=True is used, do not assign the result back to df, because the method returns None.
Standardize Pandas Column Names with a Function
The columns argument of rename() can also accept a function. Pandas calls the function once for each column label and uses the returned value as the new name.
Convert Every DataFrame Column Name to Lowercase
import pandas as pd
df = pd.DataFrame({
'Student Name': ['Ava', 'Noah'],
'Exam Score': [86, 91]
})
result = df.rename(columns=str.lower)
print(result.columns.tolist())
Output
['student name', 'exam score']
Remove Spaces and Create Lowercase Column Names
A lambda function can apply multiple transformations. The following example removes leading and trailing spaces, converts the text to lowercase, and replaces internal spaces with underscores.
import pandas as pd
df = pd.DataFrame({
' Student Name ': ['Ava', 'Noah'],
'Exam Score': [86, 91]
})
df = df.rename(
columns=lambda name: name.strip().lower().replace(' ', '_')
)
print(df.columns.tolist())
Output
['student_name', 'exam_score']
Assign New DataFrame Column Labels with set_axis()
The set_axis() method provides another way to replace all column labels. Specify axis='columns' and provide one label for each column.
import pandas as pd
df = pd.DataFrame({
'a': [10, 20],
'b': [30, 40]
})
renamed_df = df.set_axis(
['first_value', 'second_value'],
axis='columns'
)
print(renamed_df)
Output
first_value second_value
0 10 30
1 20 40
Like direct assignment to df.columns, the number of labels supplied to set_axis() must match the number of DataFrame columns.
Rename Pandas Columns Without Changing the Original DataFrame
Assign the result of rename() or set_axis() to a new variable when the original DataFrame must retain its current column names.
import pandas as pd
df = pd.DataFrame({
'name': ['Ava'],
'score': [86]
})
new_df = df.rename(columns={'score': 'exam_score'})
print(df.columns.tolist())
print(new_df.columns.tolist())
Output
['name', 'score']
['name', 'exam_score']
Handle Missing Column Names During a Pandas Rename
By default, rename() ignores dictionary keys that are not present in the DataFrame. Set errors='raise' when a missing source column should be treated as an error.
import pandas as pd
df = pd.DataFrame({
'name': ['Ava'],
'score': [86]
})
df.rename(
columns={'marks': 'exam_score'},
errors='raise'
)
Output
KeyError: "['marks'] not found in axis"
This option is useful when column names come from configuration files or external input and a spelling mistake should not pass silently.
DataFrame.columns vs rename() vs set_axis()
| Feature | df.columns = ... | df.rename() | df.set_axis() |
|---|---|---|---|
| Rename selected columns | No | Yes | No |
| Replace every column name | Yes | Yes, with a function or complete mapping | Yes |
| Changes the original by default | Yes | No | No |
| Requires matching label count | Yes | No for dictionary mappings | Yes |
| Can detect missing mapped labels | Not applicable | Yes, with errors='raise' | Not applicable |
Common Errors When Changing Pandas Column Names
- Supplying the wrong number of labels: direct assignment and
set_axis()require exactly one new label for each column. - Assigning an in-place result:
df = df.rename(..., inplace=True)replacesdfwithNone. - Renaming the index instead of columns: pass the mapping through
columns=when column labels are the intended target. - Using a source name that does not exist: inspect
df.columnsor useerrors='raise'to detect the mismatch. - Creating duplicate column names unintentionally: verify that transformed names remain unique when applying lowercase, trimming, or replacement rules.
Frequently Asked Questions About Renaming Pandas Columns
How do I rename one column in a Pandas DataFrame?
Pass a one-item dictionary to rename(), such as df.rename(columns={'old_name': 'new_name'}).
How do I rename all columns in a Pandas DataFrame?
Assign a sequence containing one new name per column to df.columns. You can also use df.set_axis(new_names, axis='columns').
Does DataFrame.rename() change the original DataFrame?
Not by default. It returns a new DataFrame. Assign the result to a variable, or pass inplace=True to modify the existing DataFrame.
How do I remove spaces from every Pandas column name?
Use a function such as df.rename(columns=lambda name: name.strip().replace(' ', '_')). Add .lower() when lowercase names are also required.
Summary of Changing Pandas DataFrame Column Names
Use df.columns or set_axis() to replace every column label, and use rename() when only selected labels need to change. A function passed to rename() can standardize all names by trimming spaces, changing letter case, or replacing characters. In this Pandas Tutorial, you learned how each approach affects the original DataFrame and how to avoid common renaming errors.
TutorialKart.com