pandas
python
data analysis
data manipulation
column renaming

Rename specific columns in pandas

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Renaming a few columns in a pandas DataFrame is a small operation that shows up constantly in real data work. The cleanest tool is DataFrame.rename, because it lets you change only the columns you care about and leave everything else untouched.

Use rename(columns=...) for Targeted Changes

The standard pattern is to pass a dictionary that maps old names to new names:

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "first_name": ["Ada", "Grace"],
6        "last_name": ["Lovelace", "Hopper"],
7        "score_2024": [98, 99],
8    }
9)
10
11renamed = df.rename(
12    columns={
13        "first_name": "given_name",
14        "score_2024": "score",
15    }
16)
17
18print(renamed.columns.tolist())

Only the keys listed in the dictionary are renamed. last_name stays exactly as it was.

That is why rename is better than reassigning df.columns when you want a selective update. Replacing df.columns requires you to supply every column name in order, which is more fragile and harder to maintain.

Decide Whether to Reassign or Modify In Place

By default, rename returns a new DataFrame:

python
renamed = df.rename(columns={"first_name": "given_name"})

If you want the original variable to carry the updated names, assign the result back:

python
df = df.rename(columns={"first_name": "given_name"})

You may also see inplace=True, but explicit reassignment is often clearer because it makes the transformation visible in the code and plays better with method chaining.

Raise Errors on Typos When Needed

One subtle behavior surprises many people: by default, pandas ignores rename keys that do not exist. That can hide spelling mistakes.

python
1df = pd.DataFrame({"name": ["Ada"], "age": [36]})
2
3df = df.rename(columns={"agge": "years"})
4print(df.columns.tolist())   # ['name', 'age']

If you want pandas to fail loudly when a column is missing, use errors="raise":

python
df = df.rename(columns={"agge": "years"}, errors="raise")

That is useful in ETL code where silent mismatches can cause later steps to break in harder-to-debug ways.

Rename Columns Conditionally

Sometimes you do not know the exact names in advance, but you still want a targeted transformation. In that case, pass a function or build the mapping dynamically.

For example, rename only columns that start with score_:

python
1df = pd.DataFrame(
2    {
3        "name": ["Ada", "Grace"],
4        "score_math": [95, 97],
5        "score_science": [96, 98],
6    }
7)
8
9mapping = {
10    column: column.replace("score_", "")
11    for column in df.columns
12    if column.startswith("score_")
13}
14
15df = df.rename(columns=mapping)
16print(df.columns.tolist())

This keeps the logic explicit while still affecting only a subset of columns.

When df.columns = ... Is Appropriate

Direct assignment to df.columns is still valid when you truly want to rename every column and you already know the full final list:

python
df.columns = ["given_name", "family_name", "score"]

That approach is not ideal for partial renames, because it couples the code to the full column order. If the source schema changes, the entire assignment can become wrong at once.

Method Chaining Example

Renaming often appears as part of a cleaning pipeline. Returning a new DataFrame makes that natural:

python
1clean = (
2    df.rename(columns={"first_name": "given_name"})
3      .assign(score=lambda frame: frame["score_2024"] / 100.0)
4      .drop(columns=["score_2024"])
5)

This style reads cleanly because each step is explicit and local.

Common Pitfalls

The most common mistake is forgetting that rename returns a new DataFrame by default. If you call it without assignment, the original object still has the old names.

Another pitfall is using df.columns = ... for a partial rename. That works only if you rewrite the full list, and it becomes brittle as soon as the schema changes.

It is also easy to miss typos because pandas ignores unknown rename keys unless you opt into errors="raise".

Finally, be careful with duplicate column names. Renaming is still possible, but later column selection can become confusing if duplicates remain in the result.

Summary

  • Use df.rename(columns={...}) when you want to rename only specific columns.
  • Reassign the result back to df unless you deliberately want a separate DataFrame.
  • Prefer rename over df.columns = ... for partial changes.
  • Use errors="raise" when silent misses would be dangerous.
  • Build the rename mapping dynamically when column patterns matter more than exact names.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.