Skip to content

Commit dded930

Browse files
dickreutervictor
authored and
victor
committed
BUG: fix for "TypeError: unorderable types" when creating MultiIndex with mixed dtypes (pandas-dev#22072)
closes pandas-dev#15457
1 parent d394855 commit dded930

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v0.24.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,7 @@ MultiIndex
626626

627627
- Removed compatibility for :class:`MultiIndex` pickles prior to version 0.8.0; compatibility with :class:`MultiIndex` pickles from version 0.13 forward is maintained (:issue:`21654`)
628628
- :meth:`MultiIndex.get_loc_level` (and as a consequence, ``.loc`` on a :class:``MultiIndex``ed object) will now raise a ``KeyError``, rather than returning an empty ``slice``, if asked a label which is present in the ``levels`` but is unused (:issue:`22221`)
629-
-
629+
- Fix ``TypeError`` in Python 3 when creating :class:`MultiIndex` in which some levels have mixed types, e.g. when some labels are tuples (:issue:`15457`)
630630

631631
I/O
632632
^^^

pandas/core/arrays/categorical.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -2538,7 +2538,10 @@ def _factorize_from_iterable(values):
25382538
ordered=values.ordered)
25392539
codes = values.codes
25402540
else:
2541-
cat = Categorical(values, ordered=True)
2541+
# The value of ordered is irrelevant since we don't use cat as such,
2542+
# but only the resulting categories, the order of which is independent
2543+
# from ordered. Set ordered to False as default. See GH #15457
2544+
cat = Categorical(values, ordered=False)
25422545
categories = cat.categories
25432546
codes = cat.codes
25442547
return codes, categories

pandas/tests/indexes/multi/test_constructor.py

+9
Original file line numberDiff line numberDiff line change
@@ -463,3 +463,12 @@ def test_tuples_with_name_string():
463463
pd.Index(li, name='abc')
464464
with pytest.raises(ValueError):
465465
pd.Index(li, name='a')
466+
467+
468+
def test_from_tuples_with_tuple_label():
469+
# GH 15457
470+
expected = pd.DataFrame([[2, 1, 2], [4, (1, 2), 3]],
471+
columns=['a', 'b', 'c']).set_index(['a', 'b'])
472+
idx = pd.MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=('a', 'b'))
473+
result = pd.DataFrame([2, 3], columns=['c'], index=idx)
474+
tm.assert_frame_equal(expected, result)

0 commit comments

Comments
 (0)