Sub topic 4
Replacing all labels at once
This chapter covers assigning a new list of labels to df.columns, and the related set_axis() method. It assumes you can create a DataFrame and select columns by label. It also assumes you know basic Python lists, dictionaries, and functions. You should have seen rename() with a dictionary from the earlier chapters.
What assignment does
rename() changes selected labels by name. Sometimes you want to replace every label in one step, for example when a file arrives with unusable headers like Unnamed: 0 or Col1, Col2, Col3. In that case you can assign a complete list of new labels to df.columns.
import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
df.columns = ["id", "qty", "price"]
print(df.columns.tolist()) # ['id', 'qty', 'price']Three facts about this form matter in practice:
- It works by position. The first new label goes to the first column, the second to the second, and so on.
- It changes the existing DataFrame. No new object is returned, and the old labels are gone.
- The list must contain exactly one label for each column.
The right-hand side does not have to be a list. Any list-like object of the right length works, including an Index, a tuple, or the result of a .str chain on df.columns. That last case is the pattern you will use for bulk cleanup in the next chapter.
Positional matching and its risk
Rename with a dictionary is safe against column reordering because it looks labels up by name. Assignment has no such protection. If the columns arrive in a different order than you expect, the labels attach to the wrong data, and no error is raised.
import pandas as pd
df = pd.DataFrame({"b": [1], "a": [2]})
# Intended: label the columns "a" and "b" in that order.
df.columns = ["a", "b"]
print(df.to_dict("records")) # [{'a': 1, 'b': 2}]The values did not move. The column that held 1 under the label b now holds 1 under the label a. If you meant to keep each value attached to its original label, assignment was the wrong tool.
Length must match
If the list is too short or too long, pandas raises a ValueError and leaves the old labels in place.
import pandas as pd
df = pd.DataFrame({"A": [1], "B": [2], "C": [3]})
try:
df.columns = ["id", "qty"]
except ValueError as exc:
print("ValueError:", exc)
# ValueError: Length mismatch: Expected axis has 3 elements, new values have 2 elements
print(df.columns.tolist()) # ['A', 'B', 'C']This is a useful guard. When a source file gains or loses a column, a fixed list of names fails loudly instead of misnaming data. If you hard-code a list, keep it next to the code that loads the file so the two stay in sync.
Index objects cannot be edited in place
df.columns is an Index, and an Index is immutable. You cannot change one label by assigning to a position.
import pandas as pd
df = pd.DataFrame({"A": [1], "B": [2]})
try:
df.columns[0] = "id"
except TypeError as exc:
print("TypeError:", exc)
# TypeError: Index does not support mutable operationsTo change a single label this way, build a new list, change the element, and assign the whole list back:
import pandas as pd
df = pd.DataFrame({"A": [1], "B": [2]})
labels = df.columns.tolist()
labels[0] = "id"
df.columns = labels
print(df.columns.tolist()) # ['id', 'B']That works, but for one or two labels rename(columns={"A": "id"}) is shorter and safer, because it matches by name.
set_axis(): the same idea without mutation
set_axis() replaces the labels on an axis and returns a new DataFrame. The original keeps its old labels. Pass axis=1 to target columns.
import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
renamed = df.set_axis(["id", "qty", "price"], axis=1)
print(df.columns.tolist()) # ['A', 'B', 'C']
print(renamed.columns.tolist()) # ['id', 'qty', 'price']The rules for length and position are the same as for assignment. The difference is that set_axis() returns a result, so it can sit in the middle of a method chain, where a statement like df.columns = ... cannot.
import pandas as pd
raw = pd.DataFrame({"X": [1, 2, 2], "Y": ["a", "b", "b"]})
clean = (
raw.set_axis(["code", "label"], axis=1)
.drop_duplicates(ignore_index=True)
)
print(clean.columns.tolist()) # ['code', 'label']
print(len(clean)) # 2Replacing labels while reading a file
When you control the load step, you can skip the cleanup and set labels as the data is read. read_csv() accepts a names argument. Combined with header=0, it discards the file's own header row and uses your names instead.
import pandas as pd
from io import StringIO
text = "Order ID,Total $\n1,10.5\n2,20.0\n"
df = pd.read_csv(StringIO(text), header=0, names=["order_id", "total"])
print(df.columns.tolist()) # ['order_id', 'total']
print(len(df)) # 2Without header=0, pandas would treat the original header as a data row when names is given. The same length rule applies here: if the file has a different number of columns than names, the result is wrong in a less obvious way than a ValueError, so check the shape after loading.
Choosing between the approaches
The diagram below summarizes how to pick a method for a given situation.
The table below lists the same options with their trade-offs.
| Approach | Matches by | Returns | Fails when |
|---|---|---|---|
| `df.rename(columns={...})` | Label name | New DataFrame | Never, but unmatched keys are ignored unless `errors="raise"` |
| `df.columns = [...]` | Position | Nothing, edits in place | List length differs from column count |
| `df.set_axis([...], axis=1)` | Position | New DataFrame | List length differs from column count |
| `read_csv(..., names=[...])` | Position | New DataFrame | File has a different column count (may not raise) |
Checking the result
After replacing labels, confirm two things: the labels are what you expect, and they still sit on the right data. A quick check is to print the labels and the first row together.
import pandas as pd
df = pd.DataFrame([[101, "Ann", 10.0]], columns=["c1", "c2", "c3"])
df.columns = ["order_id", "customer", "total"]
assert df.columns.tolist() == ["order_id", "customer", "total"]
assert df.columns.is_unique
print(df.iloc[0].to_dict())
# {'order_id': 101, 'customer': 'Ann', 'total': 10.0}Reading the first row confirms that 101 sits under order_id and Ann under customer. The is_unique check matters because assignment accepts repeated labels without complaint. A later chapter shows how repeated labels cause trouble and how to remove them.
Summary of the rules
- Assignment and
set_axis()replace every label, by position. - The new list must have the same length as the number of columns.
- Assignment edits the DataFrame in place.
set_axis()returns a new one. df.columns[0] = "x"fails because anIndexis immutable.- Neither method reorders data or checks that labels fit it.
Exercise
A DataFrame has columns ["price", "name"]. A teammate runs df.columns = ["name", "price"] to put the labels in a "nicer" order. What happens to the data, and what should they have done instead?
Show answer
The labels are swapped but the data stays where it is, so the numbers in the first column are now labelled "name" and the text values are labelled "price". Assignment matches by position and does not reorder columns. To reorder, use df[["name", "price"]]. To rename by meaning, use df.rename(columns={...}).
Exercise
You load a file with 4 columns and run df.columns = ["id", "name", "total"]. What error do you get, and are the old labels still in place afterwards?
Show answer
pandas raises ValueError with the message "Length mismatch: Expected axis has 4 elements, new values have 3 elements". The assignment is rejected, so the old labels remain.
Exercise
Write one expression that returns a new DataFrame from raw with columns named "a" and "b", leaving raw unchanged, so it can be used inside a method chain.
Show answer
raw.set_axis(["a", "b"], axis=1)