Sub topic 14
Handling duplicate column labels
This chapter assumes you know how df.columns, rename(), and duplicated() work from the earlier chapters. You should also be comfortable with Boolean masks and loc. Here we apply those tools to a related problem: two or more columns that share the same label.
How duplicate labels appear
A DataFrame does not require unique column labels. They usually show up in one of these ways:
pd.concat([a, b], axis=1)on frames that both have a column calledid.- A hand-built frame, or a file with a repeated header, loaded with a method that keeps the labels as given.
- A bulk cleanup that collapses two different labels into one. For example,
"Total $"and"Total %"both becometotalunder the snake_case recipe from earlier in this tutorial.
pd.read_csv is a partial exception. It renames repeated headers to x, x.1, and so on, so those names are unique but ugly.
Detecting duplicate labels
Index.is_unique answers the yes/no question. Index.duplicated() tells you which positions are repeats, using the same rules as Series.duplicated().
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["x", "y", "x"])
print(df.columns.is_unique) # False
print(df.columns.duplicated().tolist()) # [False, False, True]
print(df.columns[df.columns.duplicated()].unique().tolist()) # ['x']
print(type(df["x"]).__name__) # DataFrame
print(type(df["y"]).__name__) # SeriesThe last two lines show why duplicates cause trouble. Selecting a unique label returns a Series. Selecting a repeated label returns a DataFrame, so code like df["x"] + 1 or df["x"].str.lower() behaves differently or fails.
Dropping repeated labels with a mask
You can reuse the idea from the row case. Build a Boolean mask over the columns and keep the positions where it is True.
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["x", "y", "x"])
first = df.loc[:, ~df.columns.duplicated()]
print(first.columns.tolist()) # ['x', 'y']
print(first.values.tolist()) # [[1, 2], [4, 5]]
last = df.loc[:, ~df.columns.duplicated(keep="last")]
print(last.columns.tolist()) # ['y', 'x']
print(last.values.tolist()) # [[2, 3], [5, 6]]
# keep=False flags every member of a repeated group.
print(df.columns.duplicated(keep=False).tolist()) # [True, False, True]The keep option has the same meaning as in drop_duplicates():
| `keep` value | Which positions are flagged as duplicates |
|---|---|
| `"first"` (default) | Every repeat after the first occurrence |
| `"last"` | Every repeat before the last occurrence |
| `False` | All occurrences of any repeated label |
Note that drop_duplicates() has no column counterpart. A column mask in loc is the standard way to do this.
Dropping by label is not the same as dropping by content
The mask above compares labels only. It never looks at the values. In the example, the two x columns hold [1, 4] and [3, 6]. Dropping the second one discards data.
Check first whether the repeated columns are really the same data:
import pandas as pd
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["x", "y", "x"])
group = df["x"] # a DataFrame, because the label is repeated
same = all(group.iloc[:, 0].equals(group.iloc[:, i]) for i in range(1, group.shape[1]))
print(same) # FalseIf the result is False, renaming is the safer choice than dropping. If it is True, dropping loses nothing.
Why rename() cannot fix one of several repeats
A dictionary passed to rename() maps labels, not positions. If a label appears twice, both columns are renamed:
import pandas as pd
df = pd.DataFrame([[1, 2, 3]], columns=["x", "y", "x"])
print(df.rename(columns={"x": "z"}).columns.tolist()) # ['z', 'y', 'z']Both x columns became z, so the problem is unchanged. To tell repeats apart you have to work by position. Assigning to df.columns or calling set_axis() does that, because both replace labels as a whole.
Making labels unique by position
Assign a full list of new labels when you know what they should be. When you only want to number the repeats, use groupby(...).cumcount(). It counts how many times each label has appeared so far:
import pandas as pd
df = pd.DataFrame([[1, 2, 3]], columns=["x", "y", "x"])
cols = pd.Series(df.columns)
seen = cols.groupby(cols).cumcount()
df.columns = [c if n == 0 else f"{c}_{n}" for c, n in zip(cols, seen)]
print(df.columns.tolist()) # ['x', 'y', 'x_1']
print(df.columns.is_unique) # TrueThe first occurrence keeps its name, and later ones get _1, _2, and so on. Reading df["x_1"] now returns a Series.
df.set_axis(new_labels, axis=1) does the same replacement but returns a new DataFrame, which fits better in a method chain.
Finding columns that are duplicates by content
Sometimes the labels differ but the data is the same, for example after merging two exports that both carry a copy of one field. Transpose the frame so that columns become rows, then use duplicated():
import pandas as pd
wide = pd.DataFrame({"a": [1, 2], "b": [1, 2], "c": [3, 4]})
mask = wide.T.duplicated().to_numpy()
print(mask.tolist()) # [False, True, False]
print(wide.loc[:, ~mask].columns.tolist()) # ['a', 'c']There are two details to know:
- Convert the mask with
.to_numpy(). A Boolean Series would be aligned on labels, and that fails when labels are repeated. - Transposing mixed-type columns produces an object-dtype frame. This is fine for small tables but slow and memory-hungry for wide, large ones. Selecting with
locon the original frame, as above, keeps the original dtypes in the result. Callingwide.T.drop_duplicates().Twould not.
Preventing duplicate labels
Fix the cause where you can:
- In
merge(), passsuffixes=("_left", "_right")so overlapping columns get distinct names. - In
concat(axis=1), passkeys=[...]to add an outer level, or rename columns before joining. - Run the label cleanup from the earlier chapters, then check uniqueness straight after it. Collapsing labels is the most common way to create repeats by accident.
For a stricter guard, set a flag on a frame that has unique labels:
import pandas as pd
df = pd.DataFrame([[1, 2, 3]], columns=["x", "y", "x"])
try:
df.flags.allows_duplicate_labels = False
except pd.errors.DuplicateLabelError as exc:
print("DuplicateLabelError:", exc)
fixed = df.loc[:, ~df.columns.duplicated()].set_flags(allows_duplicate_labels=False)
print(fixed.flags.allows_duplicate_labels) # FalseSetting the flag on a frame that already has repeated labels raises DuplicateLabelError. On a clean frame, the flag makes later operations that would create duplicates, such as concat, raise instead of silently producing them.
Verifying the result
After any fix, confirm three things:
df.columns.is_uniqueisTrue.df.shape[1]equals the original column count minus the number of columns you meant to drop (or the same count, if you only renamed).- A spot check of values: pick a column you expected to keep and compare it with the original, using
equals().
Exercise
A frame has the columns ["id", "score", "id", "score"], and you suspect the second pair is a copy of the first. Write the steps to confirm that, then remove the copies. What goes wrong if you call df.rename(columns={"id": "id2"}) to separate them?
Show answer
Compare each repeated pair with equals(), for example df["id"].iloc[:, 0].equals(df["id"].iloc[:, 1]) and the same for "score". If both are True, run df = df.loc[:, ~df.columns.duplicated()] and check df.columns.isunique and df.shape[1] == 2. If either comparison is False, rename by position instead, for example df.columns = ["id", "score", "id1", "score_1"]. The rename() call fails to separate them because the dictionary maps labels, so both "id" columns become "id2" and the labels are still duplicated.