Skip to content
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

Raise ValueError when using levels with non-unique values in MultiIndex constructor #17557

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ def _verify_integrity(self, labels=None, levels=None):
" level (%d). NOTE: this index is in an"
" inconsistent state" % (i, label.max(),
len(level)))
for i, level in enumerate(levels):
if len(level) != len(set(level)):
raise ValueError("Level values must be unique: %s "
"on level %d" % ([value for value
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use .format syntax instead of %? I realize that other places within this file use % formatting, but there's an ongoing effort to transition all % formatting in the pandas codebase to .format, so might as well minimize the number of changes that will need to be made.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course! I do prefer .format but decided to stick with % because of the other tests. Thank you for telling me, I'll keep it in mind in future contributions :)

in level], i))

def _get_levels(self):
return self._levels
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,14 @@ def test_constructor_mismatched_label_levels(self):
with tm.assert_raises_regex(ValueError, label_error):
self.index.copy().labels = [[0, 0, 0, 0], [0, 0]]

def test_constructor_non_unique_level_values(self):
# GH #17464
with tm.assert_raises_regex(ValueError, '^Level values'):
MultiIndex(levels=[[0, 1], [0, 0, 1, 1]],
labels=[[0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1]],
names=[u'idx0', u'idx1'])

def assert_multiindex_copied(self, copy, original):
# Levels should be (at least, shallow copied)
tm.assert_copy(copy.levels, original.levels)
Expand Down