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 those labels and leave the rest alone.
What rename() does
DataFrame.rename() takes a mapping from old labels to new labels. It builds a new DataFrame with the changed labels and returns it. The data is not modified, and the original DataFrame is not modified either.
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 assignment df = df.rename(...) matters. Without it, the renamed copy is discarded and df keeps its old labels.
The dictionary keys are the labels that exist now. The values are the labels you want. Both can be any hashable value, but in practice they are nearly always strings.
Renaming only some columns
The mapping does not need to cover every column. Labels that are not in the mapping pass through unchanged. This makes rename() the right tool when you want to fix one or two labels in a wide table.
import pandas as pd
df = pd.DataFrame({
"Order ID": [1, 2],
"Customer Name": ["Ann", "Bob"],
"Total $": [10.0, 20.0],
})
renamed = df.rename(columns={"Order ID": "order_id"})
print(renamed.columns.tolist()) # ['order_id', 'Customer Name', 'Total $']
print(df.columns.tolist()) # ['Order ID', 'Customer Name', 'Total $']The second print confirms the original df still has its old labels.
Equivalent ways to call it
The columns= keyword is the clearest form because it says which axis you mean. Two other forms do the same thing.
import pandas as pd
df = pd.DataFrame({"Order ID": [1], "Total $": [10.0]})
mapping = {"Order ID": "order_id"}
a = df.rename(columns=mapping)
b = df.rename(mapping, axis="columns")
c = df.rename(mapping, axis=1)
print(a.columns.equals(b.columns), b.columns.equals(c.columns)) # True TrueIf you pass a mapping positionally and omit axis, pandas treats it as a mapping for the row index, not the columns. That is a common source of silent no-ops. Prefer columns=.
rename() also accepts index= for row labels:
import pandas as pd
df = pd.DataFrame({"x": [1, 2]})
print(df.rename(index={0: "first"}).index.tolist()) # ['first', 1]This chapter focuses on columns, but the rules below apply to both axes.
Assign the result, and avoid inplace
Because rename() returns a new object, there are two ways to keep the change:
- Assign the result:
df = df.rename(columns=mapping). - Pass
inplace=True, which modifies the DataFrame and returnsNone.
import pandas as pd
df = pd.DataFrame({"Order ID": [1]})
result = df.rename(columns={"Order ID": "order_id"}, inplace=True)
print(result) # None
print(df.columns.tolist()) # ['order_id']Assignment also lets you chain steps in one expression:
import pandas as pd
df = pd.DataFrame({"Order ID": [1, 2, 2], "Total $": [10.0, 20.0, 20.0]})
clean = (
df.rename(columns={"Order ID": "order_id", "Total $": "total"})
.drop_duplicates()
.reset_index(drop=True)
)
print(clean.columns.tolist()) # ['order_id', 'total']
print(len(clean)) # 2Unmatched keys are ignored
By default, rename() skips any key that does not match an existing label. It raises no error and no warning. A typo, a stray space, or a difference in capitalization means the rename quietly does nothing.
import pandas as pd
df = pd.DataFrame({"Order ID": [1], "Total $": [10.0]})
same = df.rename(columns={"Order Id": "order_id"}) # wrong capitalization
print(same.columns.tolist()) # ['Order ID', 'Total $']The code ran without complaint, but nothing changed. The failure shows up later, when same["order_id"] raises a KeyError. Two habits help.
The first is to check your mapping against the actual labels before renaming:
import pandas as pd
df = pd.DataFrame({"Order ID": [1], "Total $": [10.0]})
mapping = {"Order Id": "order_id", "Total $": "total"}
missing = set(mapping) - set(df.columns)
print(missing) # {'Order Id'}The second is to pass errors="raise", which turns an unmatched key into a KeyError. A later chapter covers this option in more detail.
Print df.columns.tolist() rather than df.columns when you debug. The list form shows trailing spaces and odd characters inside the quotes, which is where most mismatches hide.
Mappings are applied all at once
The mapping is applied to the original labels in one pass. It is not applied step by step, so renames do not cascade. This means swapping two labels works as you would hope:
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2]})
swapped = df.rename(columns={"a": "b", "b": "a"})
print(swapped.columns.tolist()) # ['b', 'a']
print(swapped.loc[0, "b"]) # 1The data stays where it was. The column that held 1 is now labeled b. Only the labels moved.
The same rule means a chain such as {"a": "b", "b": "c"} turns a into b and b into c. It does not turn a into c.
Renaming onto an existing label
pandas does not check whether a new name is already in use. If you rename a column to a label that another column holds, you get two columns with the same label.
import pandas as pd
df = pd.DataFrame({"a": [1], "b": [2]})
clash = df.rename(columns={"b": "a"})
print(clash.columns.tolist()) # ['a', 'a']
print(type(clash["a"]).__name__) # DataFrameSelecting clash["a"] now returns a DataFrame with two columns instead of a Series. Code that expects a single column then fails in confusing ways. Duplicate labels are legal in pandas, and a later chapter shows how to detect and remove them. For now, check that your new names do not collide with names you are keeping.
Building mappings from other sources
A hand-typed dictionary works for a few columns. For many columns, build the mapping in code.
import pandas as pd
df = pd.DataFrame({"Order ID": [1], "Customer Name": [" Ann"], "Total $": [10.0]})
# Keep a lookup table in one place
RENAMES = {
"Order ID": "order_id",
"Customer Name": "customer",
"Total $": "total",
}
# Only rename what is actually present
present = {old: new for old, new in RENAMES.items() if old in df.columns}
df = df.rename(columns=present)
print(df.columns.tolist()) # ['order_id', 'customer', 'total']Filtering the mapping to labels that are present lets one lookup table serve several files that share most, but not all, of their columns. The trade-off is that the filter also hides typos in the table, so use it only when missing columns are expected.
Choosing between rename() and other approaches
| Situation | Better choice |
|---|---|
| Fix a few specific labels | `rename(columns=mapping)` |
| Apply one rule to every label | A function passed to `rename()`, or the `.str` accessor |
| Replace every label with a known new list | Assign to `df.columns` |
The next chapters cover the second and third rows. The rule of thumb is that rename() states intent by naming the old label, so it fails less often than positional replacement when column order changes.
Practice
Exercise
You run df.rename(columns={"Total $": "total"}) on its own line, then print df.columns.tolist() and still see 'Total $'. The key is spelled correctly. What went wrong, and what are two ways to fix it?
Show answer
rename() returns a new DataFrame and does not change df, and the result was discarded. Fix it by assigning the result, df = df.rename(columns={"Total $": "total"}), or by passing inplace=True. Assignment is preferred because inplace=True returns None and breaks chaining.
Exercise
Given df = pd.DataFrame({"x": [1], "y": [2], "z": [3]}), what are the column labels after df.rename(columns={"x": "y", "y": "w", "q": "r"})? Explain each key.
Show answer
['y', 'w', 'z']. The key "x" becomes "y" and "y" becomes "w", both based on the original labels, so the renames do not cascade. The key "q" matches no column and is silently ignored. "z" is not in the mapping and stays the same.