← Back to Pandas Course | Chapter 3: DataFrame Basics | Lesson 6 of 7

Renaming columns

Rename columns with a mapping, or replace all names at once by assigning a new list.

In this page:

  1. Renaming columns
Syntax
python
df = df.rename(columns={"old_name": "new_name"})

Renaming columns

rename(columns={"old": "new"}) changes selected labels and returns a new DataFrame. Assigning df.columns = [...] replaces all names and needs the exact number. String methods on df.columns, such as str.lower(), clean names in bulk.

Note: df.columns.str.strip().str.lower() standardizes messy headers.

Example: Renaming columns

python
import pandas as pd

df = pd.DataFrame({" First Name ": ["Ann"], "AGE": [28]})
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
print(df.columns.tolist())
print(df.rename(columns={"age": "years"}))

# Output:
# ['first_name', 'age']
#   first_name  years
# 0        Ann     28
Related Topics
Common Mistakes
  1. Forgetting rename returns a copy
  2. Providing the wrong number of names
  3. Leaving stray spaces in headers
Chapter Summary
  • rename with a dict changes some labels
  • columns = [...] replaces all
  • String methods clean headers in bulk
  • rename returns a copy
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.