Sub topic 5
Cleaning messy labels into snake_case
This chapter assumes you can build a DataFrame and read df.columns. It also assumes you know rename() with a dictionary, plus Python string methods such as strip and lower. Here you will turn arbitrary column labels into consistent snake_case names in one step. You will use the .str accessor on df.columns, handle edge cases, and check that the cleanup did not merge two columns.
Why standardize labels
Labels in files exported from spreadsheets or databases often look like " Order ID", "Customer Name ", "Total $", or "shipTo-Zip". They cause three kinds of trouble:
- Stray spaces make
df["Customer Name"]fail even though the column looks right when printed. - Spaces and symbols stop you from using attribute access such as
df.total. - Mixed conventions make it easy to misspell a label in later code.
snake_case means lowercase words joined by single underscores, such as order_id. Because it is a plain convention, every label ends up predictable.
Writing one rename dictionary per file does not scale. A rule-based cleanup does: one function handles every label, including columns you have not seen yet.
The `.str` accessor on column labels
df.columns is an Index object. When its labels are strings, it has a .str accessor with the same methods a Series of strings has: strip, lower, replace, and more. Each method returns a new Index, so you can chain them and assign the result back to df.columns.
import pandas as pd
df = pd.DataFrame(columns=[" Order ID", "Customer Name ", "Total $"])
df.columns = (
df.columns.str.strip()
.str.lower()
.str.replace(r"[^0-9a-z]+", "_", regex=True)
.str.strip("_")
)
print(df.columns.tolist()) # ['order_id', 'customer_name', 'total']Each step has a job:
strip()removes leading and trailing whitespace.lower()converts every letter to lowercase.replace(r"[^0-9a-z]+", "_", regex=True)replaces each run of one or more characters that are not digits or lowercase letters with a single underscore. The+is what collapses" - "into one_instead of three.strip("_")removes underscores left at the ends. Without it,"Total $"would become"total_".
The order matters. Lowercasing before the regex lets the pattern list only a-z instead of both cases. Stripping the underscores last catches the ones the regex just created.
Always pass `regex=True`
Since pandas 2.0, str.replace treats the pattern as a literal string by default (regex=False). Earlier versions guessed. If you leave out regex=True, the pattern [^0-9a-z]+ is searched for as literal text and nothing changes. Passing the argument explicitly works the same on every version.
Handling camelCase
Labels such as customerName or orderID have no separators to replace. Lowercasing them first would produce customername, which is unreadable. Insert an underscore at each lowercase-to-uppercase boundary before lowercasing.
The following function wraps the whole cleanup so you can reuse it:
import pandas as pd
def snake_case(labels: pd.Index) -> pd.Index:
return (
labels.astype(str)
.str.strip()
.str.replace(r"([a-z0-9])([A-Z])", r"\1_\2", regex=True)
.str.lower()
.str.replace(r"[^0-9a-z]+", "_", regex=True)
.str.strip("_")
)
df = pd.DataFrame(
columns=["Order ID", "customerName", " Total $ ", "Ship-To Zip", "2024 Sales"]
)
df.columns = snake_case(df.columns)
print(df.columns.tolist())
# ['order_id', 'customer_name', 'total', 'ship_to_zip', '2024_sales']Three details in this version:
astype(str)guards against non-string labels. A file with a numeric header such as2024produces integer labels, and.strraises anAttributeErroron anIndexthat does not hold strings.- The pattern
([a-z0-9])([A-Z])captures the two characters around a boundary. The replacement\1_\2puts an underscore between them. This step must run beforelower(), because afterward the capitals are gone. - Runs of capitals are not split.
orderIDNumberbecomesorder_idnumber, notorder_id_number. If your data has labels like this, rename them explicitly with a dictionary after the bulk cleanup.
Applying the function without mutating
Assigning to df.columns changes the DataFrame you already have. When you want a new DataFrame, for example inside a method chain, use set_axis:
import pandas as pd
raw = pd.DataFrame({"Order ID": [1, 2], "Total $": [10.0, 20.0]})
clean = raw.set_axis(
raw.columns.str.lower().str.replace(r"[^0-9a-z]+", "_", regex=True).str.strip("_"),
axis="columns",
)
print(raw.columns.tolist()) # ['Order ID', 'Total $']
print(clean.columns.tolist()) # ['order_id', 'total']set_axis returns a DataFrame with the new labels, and raw stays untouched. You can also pass a function to rename(columns=...), as in df.rename(columns=str.lower). That works for simple per-label transformations. For multi-step rules like the one above, the Index.str chain is easier to read and runs on all labels at once.
Where cleanup can go wrong
Two labels collapse into one
The cleanup is many-to-one. "Total $" and "Total %" both become "total". pandas allows duplicate column labels, so nothing fails at assignment. The problem appears later, when df["total"] returns a two-column DataFrame instead of a Series. Check for collisions as part of the cleanup:
import pandas as pd
def snake_case(labels: pd.Index) -> pd.Index:
return (
labels.astype(str)
.str.strip()
.str.replace(r"([a-z0-9])([A-Z])", r"\1_\2", regex=True)
.str.lower()
.str.replace(r"[^0-9a-z]+", "_", regex=True)
.str.strip("_")
)
def clean_columns(df: pd.DataFrame) -> pd.DataFrame:
new = snake_case(df.columns)
dupes = new[new.duplicated()].unique().tolist()
if dupes:
raise ValueError(f"Cleaned labels collide: {dupes}")
return df.set_axis(new, axis="columns")
df = pd.DataFrame({"Total $": [1], "Total %": [2], "Qty": [3]})
try:
clean_columns(df)
except ValueError as exc:
print(exc) # Cleaned labels collide: ['total']Index.duplicated() marks every repeat after the first occurrence, the same way DataFrame.duplicated() marks rows. A later chapter covers repairing duplicate labels that already exist.
Characters outside `a-z`
The pattern [^0-9a-z]+ treats accented letters and non-Latin scripts as symbols. "Café" becomes "caf", which silently loses information. If your data has accents, transliterate them first:
labels.str.normalize("NFKD").str.encode("ascii", "ignore").str.decode("ascii")This converts "Café" to "Cafe". Characters with no ASCII form are dropped, so a label written entirely in another script becomes an empty string. Check for empty results before relying on the output.
Labels that start with a digit
2024_sales is a valid label for df["2024_sales"], but it is not a valid Python identifier, so df.2024_sales is a syntax error. If you want attribute access, add a prefix with .str.replace(r"^(\d)", r"_\1", regex=True) or rename those columns by hand.
Forgetting to assign
df.columns.str.lower() returns a new Index and leaves df.columns unchanged. The cleanup has an effect only when you assign the result to df.columns or pass it to set_axis.
Choosing an approach
| Situation | Approach |
|---|---|
| A few known labels need new names | `rename(columns={...})` |
| One simple transformation, such as lowercasing | `rename(columns=str.lower)` |
| A multi-step rule for all labels | `.str` chain on `df.columns` |
| You are chaining DataFrame methods | `set_axis(..., axis="columns")` |
You can combine them. Run the bulk cleanup first to remove noise, then use a dictionary for the handful of labels that still need a human-chosen name.
Verifying the result
After renaming, confirm three things:
df.columns.tolist()shows the labels you expect.df.columns.is_uniqueisTrue.df.shapeis unchanged, because renaming never adds or removes data.
import pandas as pd
df = pd.DataFrame({" Order ID": [1], "Customer Name ": ["Ann"]})
before = df.shape
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
print(df.columns.tolist()) # ['order_id', 'customer_name']
print(df.columns.is_unique) # True
print(df.shape == before) # TrueHere str.replace(" ", "_") is enough because the only separator is a single space. Without regex=True it is a literal replacement, which is what you want in this case.
Exercise
A DataFrame has the columns "Unit Price ($)", "Unit Price (€)", and "Qty". You apply the chain strip, lower, replace(r"[^0-9a-z]+", "", regex=True), strip("") to df.columns. What are the resulting labels, what problem appears, and how do you detect it before it causes errors?
Show answer
The labels become ["unitprice", "unitprice", "qty"]. "$" and "€" both fall outside [0-9a-z], so they turn into a trailing underscore that strip("") removes, and the two price columns collide. Selecting df["unitprice"] would then return a two-column DataFrame instead of a Series. Detect it by checking df.columns.isunique or by computing the new Index and testing new.duplicated().any() before assigning it. If a collision is found, rename the colliding columns explicitly, for example with rename(columns={"Unit Price ($)": "unitpriceusd", "Unit Price (€)": "unitprice_eur"}), before applying the bulk cleanup.