Sub topic 5
Cleaning messy labels into snake_case
This chapter assumes you can build a DataFrame, select columns by label, and use basic Python string methods such as strip and lower. Real data often arrives with labels like " Order ID" or "Total $". These labels have stray spaces, mixed case, and symbols, so you can't use attribute access such as df.total, and they are easy to mistype. Snake_case names (lowercase words joined by underscores) avoid these problems.
Why use the .str accessor on df.columns
df.columns is an Index object. An Index of strings has a .str accessor, the same one a Series has. Each string method you call through .str is applied to every label. The methods return a new Index, so you can chain them.
You can assign the final result back to df.columns. That replaces all labels at once, so the new Index must have exactly as many labels as the DataFrame has columns.
A snake_case pipeline
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 does one job:
strip()removes leading and trailing whitespace, so" Order ID"becomes"Order ID".lower()converts to lowercase.replace(r"[^0-9a-z]+", "_", regex=True)turns every run of characters that are not digits or lowercase letters into one underscore. Spaces,$, and punctuation all go through this step. It runs afterlower()so the pattern only needs to list lowercase letters.strip("_")removes underscores left at the ends. Without it,"Total $"would end astotal_.
The + in the pattern matters. It collapses "a - b" into a_b instead of a___b.
Doing the same with rename()
You can also pass a function to rename(). This is useful when you want a helper you can reuse and test on its own.
import re
import pandas as pd
def to_snake(label: str) -> str:
label = label.strip().lower()
label = re.sub(r"[^0-9a-z]+", "_", label)
return label.strip("_")
df = pd.DataFrame({" Order ID": [1], "Customer Name ": ["Ann"], "Total $": [10.0]})
df = df.rename(columns=to_snake)
print(df.columns.tolist()) # ['order_id', 'customer_name', 'total']The function receives each label in turn. Labels are not always strings, because a file with no header row gives integer labels. Calling .strip() on an integer raises an AttributeError. If that is possible, convert with str(label) first. The .str accessor on an Index of integers fails in a similar way.
Common errors
- Collisions. Two different labels can clean to the same name.
"Total $"and"Total %"both becometotal. The result has duplicate column labels, which later chapters cover. Check for this right after cleaning. - Lost information. Symbols such as
$and%often carry meaning. If they matter, replace them with words first, for example.str.replace("$", "usd", regex=False), before the general pattern. - Forgetting to assign.
df.columns.str.lower()returns a new Index and leavesdfunchanged.
Exercise
A column is labelled " Unit Price (USD) ". What does the pipeline strip, lower, replace with r"[^0-9a-z]+" by "", then strip "" produce?
Show answer
unitpriceusd. After strip and lower the label is "unit price (usd)". The replace step turns " " into "" and " (" into "", and the final ")" into "", giving "unitpriceusd". The last strip("_") removes the trailing underscore.