Skip to content

BUG: Add check for input array lengths in from_arrays method (GH13599) #13728

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

Closed
Closed
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.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -728,3 +728,5 @@ Bug Fixes
- Bug where ``pd.read_gbq()`` could throw ``ImportError: No module named discovery`` as a result of a naming conflict with another python package called apiclient (:issue:`13454`)
- Bug in ``Index.union`` returns an incorrect result with a named empty index (:issue:`13432`)
- Bugs in ``Index.difference`` and ``DataFrame.join`` raise in Python3 when using mixed-integer indexes (:issue:`13432`, :issue:`12814`)

- Bug in ``MultiIndex.from_arrays`` didn't check for input array lengths (:issue:`13599`)
6 changes: 6 additions & 0 deletions pandas/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,12 @@ def from_arrays(cls, arrays, sortorder=None, names=None):
name = None if names is None else names[0]
return Index(arrays[0], name=name)

# Check if lengths of all arrays are equal or not,
# raise ValueError, if not
for i in range(1, len(arrays)):
if len(arrays[i]) != len(arrays[i - 1]):
raise ValueError('all arrays must be same length')

cats = [Categorical.from_array(arr, ordered=True) for arr in arrays]
levels = [c.categories for c in cats]
labels = [c.codes for c in cats]
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/indexes/test_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,27 @@ def test_from_arrays_index_series_period(self):

tm.assert_index_equal(result, result2)

def test_from_arrays_different_lengths(self):
# GH13599
idx1 = [1, 2, 3]
idx2 = ['a', 'b']
assertRaisesRegexp(ValueError, '^all arrays must be same length$',
MultiIndex.from_arrays, [idx1, idx2])

def test_from_arrays_different_lengths_first_array_zero_length(self):
# GH13599
idx1 = []
idx2 = ['a', 'b']
assertRaisesRegexp(ValueError, '^all arrays must be same length$',
MultiIndex.from_arrays, [idx1, idx2])

def test_from_arrays_different_lengths_second_array_zero_length(self):
# GH13599
idx1 = [1, 2, 3]
idx2 = []
assertRaisesRegexp(ValueError, '^all arrays must be same length$',
MultiIndex.from_arrays, [idx1, idx2])

def test_from_product(self):

first = ['foo', 'bar', 'buz']
Expand Down