Sub topic 4
Replacing all labels at once
This chapter assumes you can build a DataFrame, read df.columns, and work with Python lists. You have already seen rename() change selected labels. Here you replace every label in one step by assigning to df.columns.
Assigning a list to df.columns
df.columns is an attribute you can read and write. If you assign a list, pandas builds a new Index from it and attaches it to the DataFrame. The list must contain exactly one label for each column, in the same order as the current columns.
import pandas as pd
df = pd.DataFrame({
"Order ID": [1, 2],
"Customer Name": ["Ann", "Bob"],
"Total $": [10.0, 20.0],
})
df.columns = ["order_id", "customer", "total"]
print(df.columns.tolist()) # ['order_id', 'customer', 'total']Unlike rename(), this changes df itself. No new DataFrame is returned, so there is nothing to reassign. The data is untouched. Only the labels change.
How the pieces fit
Length must match
pandas refuses to assign a list of the wrong size. The old labels stay in place, so a failed assignment does no damage.
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2], "c": [3]})
try:
df.columns = ["x", "y"]
except ValueError as exc:
print("ValueError:", exc)
print(df.columns.tolist()) # ['a', 'b', 'c']Matching is by position, not by name
This is the main risk of the approach. rename() looks labels up by name. Assignment never looks at the old names, only at positions. If an upstream step reorders the columns, your list is applied to the wrong columns and no error appears.
import pandas as pd
df = pd.DataFrame({"name": ["Ann"], "age": [30]})
df = df[["age", "name"]] # order changed upstream
df.columns = ["name", "age"] # positional: labels now swapped
print(df.to_dict("records")) # [{'name': 30, 'age': 'Ann'}]The values did not move, but the labels did. Assignment is safe when you control the order, for example right after reading a file with a known layout. Otherwise prefer rename() with a dictionary.
A non-mutating alternative: set_axis()
If you want a new DataFrame, for example inside a method chain, use set_axis(). It takes the same kind of list and returns a copy with the new labels.
import pandas as pd
df = pd.DataFrame({"A": [1], "B": [2]})
renamed = df.set_axis(["alpha", "beta"], axis=1)
print(renamed.columns.tolist()) # ['alpha', 'beta']
print(df.columns.tolist()) # ['A', 'B']Choosing between the options
| Situation | Tool |
|---|---|
| Change a few labels by name | `rename(columns={...})` |
| Replace every label, order is known | `df.columns = [...]` |
| Replace every label inside a chain | `set_axis([...], axis=1)` |
| Transform existing labels | A function or the `.str` accessor, covered next |
Exercise
A DataFrame has columns ["Date", "Amount", "Note"]. You run df.columns = ["date", "amount"]. What happens, and what are the column labels afterwards?
Show answer
pandas raises a ValueError because the list has 2 labels but the DataFrame has 3 columns. The assignment is rejected, so the labels remain ["Date", "Amount", "Note"].
Exercise
Why can df.columns = ["id", "name"] silently mislabel data, while df.rename(columns={"A": "id", "B": "name"}) cannot?
Show answer
Assignment is positional, so if the columns were reordered earlier, the new labels land on the wrong columns without any error. rename() matches by the old label, so each new name attaches to the column it was meant for.