Sub topic 1
Looking at Your Column Labels
Prerequisites
Assume you can create a pandas DataFrame, select columns by label, use Python dictionaries and functions, and call string methods such as strip() and lower().
Inspecting Column Labels
Column labels are the names in df.columns. Inspect them before changing data. The result is an Index, which behaves like an ordered collection of labels.
import pandas as pd
df = pd.DataFrame({
"Order ID": [1, 2],
"Customer Name": ["Ann", "Bob"],
"Total $": [10.0, 20.0],
})
print(df.columns.tolist())
# ['Order ID', 'Customer Name', 'Total $']Renaming Specific Columns
Use rename() with a dictionary when only some labels need changing. The dictionary maps each old label to its new label. rename() returns a new DataFrame, so assign the result.
df = df.rename(columns={
"Order ID": "order_id",
"Customer Name": "customer",
"Total $": "total",
})
print(df.columns.tolist())
# ['order_id', 'customer', 'total']A mapping key that does not match a label is ignored by default. Use errors="raise" when a missing label indicates a mistake.
Renaming Every Column with a Function
Pass a function to rename(columns=...) to apply it to every label:
lowered = df.rename(columns=str.lower)The function must accept one label and return its replacement. This approach is useful for simple transformations.
Replacing All Labels at Once
Assign a complete sequence to df.columns when you want to replace every label. The sequence must have exactly as many items as the DataFrame has columns.
df.columns = ["id", "name", "amount"]This changes the labels in place. It does not change the data stored in the columns.
Cleaning Messy Labels into snake_case
For systematic cleanup, use the .str accessor on df.columns. It applies string operations to all labels.
df.columns = (
df.columns.str.strip()
.str.lower()
.str.replace(r"[^0-9a-z]+", "_", regex=True)
.str.strip("_")
)This removes surrounding spaces, lowercases text, replaces runs of non-alphanumeric characters with underscores, and removes extra underscores at the ends.
Exercise
Which method should you use to turn every label into lowercase without writing a mapping?
Show answer
Use df.rename(columns=str.lower), then assign the returned DataFrame if you want to keep the change.