Sub topic 2
Renaming specific columns with rename()
This chapter assumes you can create a DataFrame, select columns by label, and read a Python dictionary. The previous chapter showed how to inspect labels with df.columns. Here you change some of them.
Why rename selected columns
Data from spreadsheets and exports often has labels such as Order ID or Total $. These contain spaces and symbols, so you can't use attribute access like df.total, and the labels are easy to mistype. Renaming gives each column a short, predictable name.
DataFrame.rename() changes only the labels you name. Every other column keeps its current label.
The dictionary mapping
Pass a dictionary to the columns argument. Each key is an existing label. Each value is the new label.
import pandas as pd
df = pd.DataFrame({
"Order ID": [1, 2, 2, 3],
"Customer Name": ["Ann", "Bob", "Bob", "Cy"],
"Total $": [10.0, 20.0, 20.0, 5.0],
})
df = df.rename(columns={
"Order ID": "order_id",
"Customer Name": "customer",
"Total $": "total",
})
print(df.columns.tolist()) # ['order_id', 'customer', 'total']The line df = df.rename(...) matters. rename() returns a new DataFrame and leaves the original unchanged. If you call it without assigning the result, nothing visible happens.
Renaming only some columns
You don't have to list every column. Suppose you only want to fix one label:
import pandas as pd
df = pd.DataFrame({"Order ID": [1, 2], "region": ["east", "west"]})
renamed = df.rename(columns={"Order ID": "order_id"})
print(renamed.columns.tolist()) # ['order_id', 'region']
print(df.columns.tolist()) # ['Order ID', 'region']The region column is untouched. The second print confirms that df still has its old labels, because rename() worked on a copy.
The same call, written another way
columns={...} is the clearest form. You can also pass the dictionary first and name the axis:
import pandas as pd
df = pd.DataFrame({"A": [1], "B": [2]})
same = df.rename({"A": "alpha"}, axis="columns")
print(same.columns.tolist()) # ['alpha', 'B']Without axis="columns", a bare dictionary renames the row index instead. Prefer the columns= keyword so the intent is obvious to the next reader.
Things to check after renaming
- Labels in the dictionary must match exactly, including case and spaces.
"order id"will not match"Order ID". - A key that matches no column is skipped without any error. A typo in the mapping can therefore leave a column unchanged. The pitfalls chapter shows how to make this fail loudly.
- Print
df.columns.tolist()after the call. It is the quickest way to confirm the new names.
Summary
df.rename(columns={old: new})changes only the columns you list.- The method returns a new DataFrame, so assign the result.
- Use the
columns=keyword so you don't rename the row index by accident.
Exercise
You run df.rename(columns={"Total $": "total"}) on its own line, then print df.columns.tolist(). The output still shows 'Total $'. Give two possible reasons.
Show answer
The first reason is that the result was not assigned. rename() returns a new DataFrame and does not modify df, so you need df = df.rename(...). The second is that the key did not match exactly, for example because of a trailing space or different capitalization. Unmatched keys are ignored silently, so the label stays the same.
Exercise
Given df = pd.DataFrame({"Name": ["Ann"], "Age": [30], "City": ["Oslo"]}), write one statement that renames only Name to name and City to city, and stores the result in df.
Show answer
df = df.rename(columns={"Name": "name", "City": "city"})