Sub topic 1
Looking at your column labels
Before you rename anything, you need to see what the labels are. This chapter shows how to inspect df.columns and spot the problems that later chapters fix.
Prerequisites
This chapter assumes you can:
- Create a pandas DataFrame and select columns by label.
- Use basic Python dictionaries and functions.
- Use string methods such as
stripandlower.
Column labels are an Index
The labels of a DataFrame are stored in df.columns. It is a pandas Index object, not a plain list. It is ordered, it can hold repeated values, and it supports vectorized string methods through .str.
import pandas as pd
df = pd.DataFrame({
" Order ID": [1, 2, 3],
"Customer Name ": ["Ann", "Bob", "Cy"],
"Total $": [10.0, 20.0, 5.0],
})
print(df.columns)
print(df.columns.tolist())
print(len(df.columns))The first print shows the Index with its dtype='object'. The second converts it to a list, which is easier to read when labels contain spaces. Notice the leading space in " Order ID" and the trailing space in "Customer Name ". Both are invisible in a table display but they are part of the label.
What to look for
Inspect the label list for these problems:
| Problem | Example | Effect |
|---|---|---|
| Leading or trailing spaces | `"Customer Name "` | `df["Customer Name"]` raises `KeyError` |
| Mixed case | `"Order ID"`, `"order id"` | Labels that look alike are different |
| Spaces and symbols | `"Total $"` | You cannot use attribute access such as `df.total` |
| Duplicate labels | `"x"` twice | `df["x"]` returns a DataFrame, not a Series |
Labels are matched exactly. A trailing space makes a different label.
try:
df["Customer Name"]
except KeyError as exc:
print("KeyError:", exc)
print(df["Customer Name "].tolist())The first lookup fails because the real label has a trailing space. Printing repr output through tolist() is a quick way to reveal such cases.
Checking labels quickly
These checks take a few seconds and catch most problems.
labels = df.columns
print(labels.is_unique) # True when no label repeats
print(labels.duplicated().tolist()) # flags each repeat after the first
print((labels != labels.str.strip()).tolist()) # True where whitespace is present
print(df.dtypes) # label and dtype togetheris_unique is True when no label repeats. duplicated() marks repeats. Comparing labels with their stripped version marks labels that have extra whitespace. For this DataFrame the whitespace check gives [True, True, False].
Labels do not have to be strings. A DataFrame built from a NumPy array has integer labels 0, 1, 2. Calling .str methods on such an index raises an AttributeError, so check df.columns.dtype before you clean labels in bulk.
Key points
df.columnsis anIndexof labels, and labels match exactly.- Whitespace, mixed case, symbols, and repeated labels are the usual problems.
is_uniqueandduplicated()check for repeats. Comparing against.str.strip()finds whitespace.
Exercise
A DataFrame has the columns ["id", "Name ", "name"]. Which label causes df["Name"] to fail, and does df.columns.is_unique return True or False?
Show answer
df["Name"] fails because the real label is "Name " with a trailing space, so there is no exact match. is_unique returns True, because "id", "Name ", and "name" are three different labels.