Renaming columns in pandas changes the labels used to select, join, export, and report a DataFrame without changing the row data underneath. Use it after reading files with awkward headers, preparing data for downstream code, or normalizing labels into a project naming style.
DataFrame.rename() is the clearest choice when only selected columns need new names. The columns mapping uses current labels as dictionary keys and replacement labels as values, so labels omitted from the mapping remain unchanged.
By default, rename() returns a new DataFrame. In current pandas releases, the old copy argument is ignored under Copy-on-Write behavior, so assign the returned object to a new variable or back to the original variable deliberately. Add errors=“raise” while building the mapping so a mistyped old column name stops the script instead of leaving an expected rename undone.
import pandas as pd sales = pd.DataFrame({ "Customer ID": [101, 102, 103], "Order Total": [45.50, 72.00, 38.25], "Order Date": ["2026-06-01", "2026-06-02", "2026-06-03"], }) rename_map = { "Customer ID": "customer_id", "Order Total": "order_total", "Order Date": "order_date", } renamed = sales.rename(columns=rename_map, errors="raise") print(renamed) print() print("columns:", renamed.columns.tolist()) print("original:", sales.columns.tolist()) print("total:", renamed["order_total"].sum())
The left side of each mapping entry must match the current column label exactly. Replace the sample sales object with the DataFrame already loaded in the working script.
$ python3 rename-columns.py customer_id order_total order_date 0 101 45.50 2026-06-01 1 102 72.00 2026-06-02 2 103 38.25 2026-06-03 columns: ['customer_id', 'order_total', 'order_date'] original: ['Customer ID', 'Order Total', 'Order Date'] total: 155.75
The original sales labels remain unchanged because the script assigns the returned DataFrame to renamed.
sales = sales.rename(columns=rename_map, errors="raise")
Without errors="raise", mapping keys that do not match an existing column are ignored and the old label stays in place.
sales["order_total"].sum()
If the expression raises KeyError, print sales.columns.tolist() and fix the mapping key or replacement label before continuing.