Skip to content

Commit 8763b5e

Browse files
ZanirPZanirP
ZanirP
authored and
ZanirP
committed
Bug Fixed Issue GH61475
1 parent 53e39f7 commit 8763b5e

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

pandas/core/reshape/melt.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ def melt(
173173
1 b B E 3
174174
2 c B E 5
175175
"""
176+
# GH61475 - prevent AttributeError when duplicate column in id_vars
177+
if id_vars and any(frame.columns.tolist().count(col) > 1 for col in id_vars):
178+
raise ValueError("id_vars cannot contain duplicate columns.")
176179
if value_name in frame.columns:
177180
raise ValueError(
178181
f"value_name ({value_name}) cannot match an element in "
@@ -239,9 +242,6 @@ def melt(
239242
mdata: dict[Hashable, AnyArrayLike] = {}
240243
for col in id_vars:
241244
id_data = frame.pop(col)
242-
# GH61475 - prevent AttributeError when duplicate column
243-
if not hasattr(id_data, "dtype"):
244-
raise Exception(f"{col} is a duplicate column header")
245245
if not isinstance(id_data.dtype, np.dtype):
246246
# i.e. ExtensionDtype
247247
if num_cols_adjusted > 0:

pandas/tests/reshape/test_melt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -558,9 +558,9 @@ def test_melt_multiindex_columns_var_name_too_many(self):
558558
def test_melt_duplicate_column_header_raises(self):
559559
# GH61475
560560
df = DataFrame([[1, 2, 3], [3, 4, 5]], columns=["A", "A", "B"])
561-
msg = "A is a duplicate column header"
561+
msg = "id_vars cannot contain duplicate columns."
562562

563-
with pytest.raises(Exception, match=msg):
563+
with pytest.raises(ValueError, match=msg):
564564
df.melt(id_vars=["A"], value_vars=["B"])
565565

566566

0 commit comments

Comments
 (0)