Sub topic 14
Handling duplicate column labels
This chapter assumes you can rename columns with rename() and assign to df.columns. It also assumes you know what a boolean mask is. Everything so far has treated duplicates as repeated rows. Here the repeats are in the column labels themselves, which pandas allows but which causes problems.
Why duplicate labels cause trouble
A DataFrame does not require unique column labels. This happens after concatenating tables, merging files, or reading a CSV whose header repeats a name. Selecting a repeated label no longer returns a Series. It returns a DataFrame holding every column with that label.
import pandas as pd
df = pd.DataFrame([[1, 2, 3]], columns=["x", "y", "x"])
print(df.columns.duplicated().tolist()) # [False, False, True]
print(type(df["x"]).__name__) # DataFrame
print(df.rename(columns={"x": "a"}).columns.tolist()) # ['a', 'y', 'a']The last line shows a second hazard. A rename mapping matches by label, so it changes every column with that label and leaves the duplicates in place.
Flagging repeated labels
Index.duplicated() works like DataFrame.duplicated(), but it checks labels instead of row values. It returns a boolean array with one entry per column. By default, keep="first" marks every repeat after the first occurrence as True.
print(df.columns.duplicated().sum()) # 1
print(df.columns.is_unique) # FalseUse is_unique as a quick check before a step that needs one column per label.
Keeping one column per label
To drop the repeats, invert the mask and pass it to loc. The : before the comma keeps all rows, and the mask after it selects columns.
first = df.loc[:, ~df.columns.duplicated()]
last = df.loc[:, ~df.columns.duplicated(keep="last")]
print(first.columns.tolist()) # ['x', 'y']
print(last.columns.tolist()) # ['y', 'x']The keep option behaves as it does for rows. keep="last" keeps the final occurrence, which also changes the column order.
Keeping every column with unique names
Dropping columns discards data. If the repeated columns hold different values, give each one a distinct name instead. Number the repeats within each label group, then build new labels.
cols = pd.Series(df.columns)
repeat = cols.groupby(cols).cumcount()
df.columns = [c if n == 0 else f"{c}_{n}" for c, n in zip(cols, repeat)]
print(df.columns.tolist()) # ['x', 'y', 'x_1']cumcount() gives 0 for the first x and 1 for the second. The first keeps its name and the later ones get a numeric suffix. You assign the whole list to df.columns, so each column is renamed by position and not by label.
Identical labels versus identical values
Two different problems are easy to confuse:
| Situation | What is repeated | Tool |
|---|---|---|
| Duplicate labels | The column name | `df.columns.duplicated()` |
| Duplicate values | The contents of two columns | `df.T.duplicated()` |
Transposing with df.T turns columns into rows, so duplicated() can compare them. It copies the data and can mix dtypes, so use it only on small tables.
Verify the fix
After either approach, confirm the result before moving on:
df.columns.is_uniqueisTrue.df.shape[1]matches the number of columns you expect.df["x"]returns a Series, not a DataFrame.
Exercise
A DataFrame has the columns ["a", "b", "a"]. What does ~df.columns.duplicated(keep="last") return, and which columns does df.loc[:, mask] keep?
Show answer
With keep="last", the first "a" is flagged as a duplicate, so duplicated returns [True, False, False]. Inverting gives [False, True, True]. The mask keeps "b" and the last "a", in that order.