Skip to content

Commit 8981a0f

Browse files
ZanirPZanirPZanirPmroeschke
authored
BUG: Raise clear error for duplicate id_vars in melt (GH61475) (#61484)
* BUG: Raise clear error for duplicate id_vars in melt (GH61475) * Bug Fixed Issue GH61475 * if statement changes * Update pandas/core/reshape/melt.py --------- Co-authored-by: ZanirP <zanir@DESKTOP-JOHE35M> Co-authored-by: ZanirP <[email protected]> Co-authored-by: Matthew Roeschke <[email protected]>
1 parent 2378141 commit 8981a0f

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,7 @@ Reshaping
851851
- Bug in :meth:`DataFrame.stack` with the new implementation where ``ValueError`` is raised when ``level=[]`` (:issue:`60740`)
852852
- Bug in :meth:`DataFrame.unstack` producing incorrect results when manipulating empty :class:`DataFrame` with an :class:`ExtentionDtype` (:issue:`59123`)
853853
- Bug in :meth:`concat` where concatenating DataFrame and Series with ``ignore_index = True`` drops the series name (:issue:`60723`, :issue:`56257`)
854+
- Bug in :func:`melt` where calling with duplicate column names in ``id_vars`` raised a misleading ``AttributeError`` (:issue:`61475`)
854855

855856
Sparse
856857
^^^^^^

pandas/core/reshape/melt.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,10 @@ def melt(
182182
value_vars_was_not_none = value_vars is not None
183183
value_vars = ensure_list_vars(value_vars, "value_vars", frame.columns)
184184

185+
# GH61475 - prevent AttributeError when duplicate column in id_vars
186+
if len(frame.columns.get_indexer_for(id_vars)) > len(id_vars):
187+
raise ValueError("id_vars cannot contain duplicate columns.")
188+
185189
if id_vars or value_vars:
186190
if col_level is not None:
187191
level = frame.columns.get_level_values(col_level)

pandas/tests/reshape/test_melt.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,14 @@ def test_melt_multiindex_columns_var_name_too_many(self):
555555
):
556556
df.melt(var_name=["first", "second", "third"])
557557

558+
def test_melt_duplicate_column_header_raises(self):
559+
# GH61475
560+
df = DataFrame([[1, 2, 3], [3, 4, 5]], columns=["A", "A", "B"])
561+
msg = "id_vars cannot contain duplicate columns."
562+
563+
with pytest.raises(ValueError, match=msg):
564+
df.melt(id_vars=["A"], value_vars=["B"])
565+
558566

559567
class TestLreshape:
560568
def test_pairs(self):

0 commit comments

Comments
 (0)