Skip to content

BUG: wide_to_long should check for unique id vars (#16382) #16403

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.20.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,10 @@ Reshaping
^^^^^^^^^

- Bug in ``DataFrame.stack`` with unsorted levels in MultiIndex columns (:issue:`16323`)
- Bug in ``pd.wide_to_long()`` where no error was raised when ``i`` was not a unique identifier (:issue:`16382`)
- Bug in ``Series.isin(..)`` with a list of tuples (:issue:`16394`)


Numeric
^^^^^^^
- Bug in .interpolate(), where limit_direction was not respected when limit=None (default) was passed (:issue:16282)
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -1046,6 +1046,9 @@ def melt_stub(df, stub, i, j, value_vars, sep):
else:
i = list(i)

if df[i].duplicated().any():
raise ValueError("the id variables need to uniquely identify each row")

value_vars = list(map(lambda stub:
get_var_names(df, stub, sep, suffix), stubnames))

Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/reshape/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,3 +976,14 @@ def test_multiple_id_columns(self):
exp_frame = exp_frame.set_index(['famid', 'birth', 'age'])[['ht']]
long_frame = wide_to_long(df, 'ht', i=['famid', 'birth'], j='age')
tm.assert_frame_equal(long_frame, exp_frame)

def test_non_unique_idvars(self):
# GH16382
# Raise an error message if non unique id vars (i) are passed
df = pd.DataFrame({
'A_A1': [1, 2, 3, 4, 5],
'B_B1': [1, 2, 3, 4, 5],
'x': [1, 1, 1, 1, 1]
})
with pytest.raises(ValueError):
wide_to_long(df, ['A_A', 'B_B'], i='x', j='colname')