How do I rename columns in a pandas DataFrame?
Short answer
Use rename with a dictionary to change named columns, or assign a full list to df.columns to replace them all. rename returns a new frame unless you reassign or pass inplace.
The short version
Use rename(columns={...}) with a dictionary mapping old names to new ones when you want to change a few columns. To replace every name at once, assign a list to df.columns. Like most pandas methods, rename returns a new frame, so reassign the result.
Renaming selected columns
import pandas as pd
df = pd.DataFrame({"Prod Name": ["pen"], "Unit Price": [2]})
df = df.rename(columns={"Prod Name": "product", "Unit Price": "price"})
print(df.columns.tolist()) # ['product', 'price']
Only the columns you name are changed, and any name not in the dictionary is left alone, which makes this safe on a wide frame.
Replacing all names at once
If you want to set every column name, assign a list of the right length.
df.columns = ["product", "price"]
This is quick, but the list must match the column count and order exactly, so it is easy to misalign on a wide frame. Prefer the dictionary form when you only need to fix a few.
Cleaning messy headers in bulk
Real files often arrive with mixed case and spaces. A small transformation tidies them all consistently.
df.columns = (
df.columns
.str.strip()
.str.lower()
.str.replace(" ", "_")
)
This lowercases, trims stray spaces and swaps spaces for underscores, giving predictable names like product and unit_price that are easy to type and reference.
The reassign reminder
This line looks like it renames but changes nothing, because the result is discarded:
df.rename(columns={"price": "cost"}) # result thrown away
Either reassign to df, or pass inplace=True. Reassigning is usually clearer and works naturally in a chain of steps.
Renaming the index
The same method renames index labels through the index argument, which is useful after grouping when the index holds meaningful values.
df.rename(index={0: "first_row"})