Sub topic 1
Looking at your column labels
Before you rename a column, you need to know exactly what its label is. Labels that look the same in a printout can differ by a trailing space, a letter case, or a data type. This chapter covers how to inspect df.columns, what kinds of problems to look for, and how to spot them with code instead of by eye. The later chapters on renaming build on this.
Prerequisites
This chapter assumes you can:
- Create a pandas DataFrame and select columns by label, such as
df["total"]. - Read basic Python dictionaries and lists.
- Use string methods such as
strip()andlower().
What df.columns is
df.columns is a pandas Index object. It is an ordered collection of labels, one per column. It behaves like a list in some ways (you can loop over it, take its length, and slice it), but it has three differences that matter for cleanup:
- It is immutable. You cannot change one label in place.
- It can hold any hashable value, not only strings.
- It is allowed to contain the same label more than once.
Start with a DataFrame that has some typical problems:
import pandas as pd
df = pd.DataFrame({
" Order ID": [1, 2],
"Customer Name ": ["Ann", "Bob"],
"Total $": [10.0, 20.0],
"total $": [1.0, 2.0],
})
print(df.columns.tolist())
# [' Order ID', 'Customer Name ', 'Total $', 'total $']
print(len(df.columns))
# 4tolist() gives you a plain Python list, which prints each label inside quotes. The quotes are what make the leading space in ' Order ID' and the trailing space in 'Customer Name ' visible. Printing the DataFrame itself hides both, because the header is padded for display.
Making problems visible with repr()
A plain print(label) shows a trailing space as nothing at all. Use repr() and len() to see what is really stored:
for label in df.columns:
print(repr(label), len(label))
# ' Order ID' 9
# 'Customer Name ' 14
# 'Total $' 7
# 'total $' 7' Order ID' has length 9, but Order ID has only 8 characters. That difference is the leading space. If you try df["Order ID"] on this DataFrame, you get a KeyError, because no label matches exactly.
Pandas compares labels exactly, including case and whitespace. "Total $" and "total $" are two different labels, even though a person reads them as the same.
Checking labels with code
Eyeballing a list works for four columns. It does not work for 80. The .str accessor on an Index lets you test every label at once.
stripped = df.columns.str.strip()
padded = df.columns[df.columns != stripped]
print(padded.tolist())
# [' Order ID', 'Customer Name ']Here df.columns != stripped produces a boolean array, one value per label. Using that array to index df.columns returns only the labels that change when stripped.
You can run a similar check for other problems:
print(df.columns[df.columns.str.contains(r"[^0-9A-Za-z_]")].tolist())
# [' Order ID', 'Customer Name ', 'Total $', 'total $']This regular expression matches any character that is not a letter, digit, or underscore. It flags all four labels here, since each contains a space or a dollar sign. After cleanup, an empty result from this check tells you every label is a safe identifier.
What to look for
The table lists the usual problems, how to detect each one, and why it matters.
| Problem | Example | How to detect | Why it matters |
|---|---|---|---|
| Leading or trailing whitespace | `"Customer Name "` | `df.columns != df.columns.str.strip()` | Selection with the visible name raises `KeyError` |
| Inconsistent case | `"Total $"` vs `"total $"` | `df.columns.str.lower().duplicated()` | Looks like one column, behaves as two |
| Spaces and symbols | `"Total $"` | `str.contains(r"[^0-9A-Za-z_]")` | Blocks attribute access like `df.total` and forces bracket syntax |
| Non-string labels | `2024` | `df.columns.map(type)` | `df["2024"]` fails, `df[2024]` works |
| Repeated labels | `"x"` twice | `df.columns.is_unique` | `df["x"]` returns a DataFrame, not a Series |
Non-string labels
Column labels do not have to be strings. This happens often when a header row was read as data, or when years are used as column names.
wide = pd.DataFrame([[5, "a"]], columns=[2024, "name"])
print(wide.columns.dtype) # object
print(wide[2024].tolist()) # [5]
print(wide.columns.map(type).tolist())
# [<class 'int'>, <class 'str'>]
try:
wide["2024"]
except KeyError as exc:
print("KeyError:", exc) # KeyError: '2024'The Index dtype is object because it mixes integers and strings. This matters for cleanup, because .str methods turn non-string items into missing values. If an Index has mixed types, convert it first with df.columns.astype(str). Do that before you apply any .str chain.
Labels cannot be edited one at a time
Because an Index is immutable, assigning to one position fails:
try:
df.columns[0] = "order_id"
except TypeError as exc:
print("TypeError:", type(exc).__name__)
# TypeError: TypeErrorThis is a deliberate design choice. The label set is part of how pandas finds data, so it is changed by replacing the whole Index or by creating a new DataFrame with rename(). Both approaches are covered in the next chapters. For now, remember that "inspect" and "modify" are separate steps, and inspection never changes your data.
Duplicate labels
Pandas permits two columns with the same label. This often comes from concatenating tables or from a file whose header repeats a name.
dup = pd.DataFrame([[1, 2, 3]], columns=["x", "y", "x"])
print(dup.columns.is_unique) # False
print(dup.columns.duplicated().tolist()) # [False, False, True]
print(dup["x"].shape) # (1, 2)is_unique answers a yes-or-no question quickly. duplicated() gives one flag per label, and marks the second and later occurrences as True. Selecting dup["x"] returns a two-column DataFrame instead of a Series. Code that expects a Series then fails somewhere downstream, often with a confusing message.
A later chapter in this tutorial shows how to remove repeated columns. For now, make is_unique part of your inspection routine.
Putting it together: an audit routine
A short function can run all the checks and report the results. It does not change the DataFrame.
import pandas as pd
def audit_columns(df):
labels = df.columns
as_text = labels.astype(str)
return {
"count": len(labels),
"unique": bool(labels.is_unique),
"non_string": labels[[not isinstance(x, str) for x in labels]].tolist(),
"padded": labels[as_text != as_text.str.strip()].tolist(),
"case_clash": as_text[as_text.str.lower().duplicated(keep=False)].tolist(),
}
messy = pd.DataFrame(
[[1, 2, 3, 4]],
columns=[" Order ID", "Total $", "total $", 2024],
)
print(audit_columns(messy))
# {'count': 4, 'unique': True, 'non_string': [2024],
# 'padded': [' Order ID'], 'case_clash': ['Total $', 'total $']}Three details in this function are worth noting:
astype(str)makes the string checks safe even when a label is an integer.keep=Falseinduplicated()flags every member of a clash, not only the later ones, so you see bothTotal $andtotal $.labels.is_uniquereturns a NumPy boolean, so it is wrapped inbool()to keep the output plain.
The flow of an inspection looks like this:
Common mistakes
- Trusting the printed table header. Display padding hides leading and trailing spaces. Use
tolist()orrepr(). - Applying
.strmethods to an Index that contains integers. Those items becomeNaN, which can later breakrename()or assignment. Convert withastype(str)first. - Treating
df.columnslike a list you can edit. It is read-only per element. - Assuming labels are unique. Check
is_uniquebefore selecting by name.
Exercise
A DataFrame has columns ["id", "Name ", "name", 2025]. Using only inspection, without changing the DataFrame, which two labels would a check for case clashes flag after stripping and lowercasing, and which check would flag the label 2025?
Show answer
Stripping and lowercasing turns "Name " into "name", so "Name " and "name" clash and both are flagged (use duplicated(keep=False) to see both). The label 2025 is flagged by a type check such as df.columns.map(type) or isinstance(x, str), because it is an integer, not a string. Convert with df.columns.astype(str) before using .str methods.