Skip to content

Commit 9a2d9ea

Browse files
author
Khor Chean Wei
authored
Bug fix - cannot construct Index of empty tuples (#46238)
1 parent ccfd0d6 commit 9a2d9ea

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ MultiIndex
485485
- Bug in :meth:`DataFrame.loc` raising when slicing a :class:`MultiIndex` with a negative step size and slicing a non-int labeled index level (:issue:`46156`)
486486
- Bug in :meth:`Series.to_numpy` where multiindexed Series could not be converted to numpy arrays when an ``na_value`` was supplied (:issue:`45774`)
487487
- Bug in :class:`MultiIndex.equals` not commutative when only one side has extension array dtype (:issue:`46026`)
488-
-
488+
- Bug in :meth:`MultiIndex.from_tuples` cannot construct Index of empty tuples (:issue:`45608`)
489489

490490
I/O
491491
^^^

pandas/core/indexes/multi.py

+12
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,18 @@ def from_tuples(
546546
tuples = list(tuples)
547547
tuples = cast(Collection[Tuple[Hashable, ...]], tuples)
548548

549+
# handling the empty tuple cases
550+
if len(tuples) and all(isinstance(e, tuple) and not e for e in tuples):
551+
codes = [np.zeros(len(tuples))]
552+
levels = [Index(com.asarray_tuplesafe(tuples, dtype=np.dtype("object")))]
553+
return cls(
554+
levels=levels,
555+
codes=codes,
556+
sortorder=sortorder,
557+
names=names,
558+
verify_integrity=False,
559+
)
560+
549561
arrays: list[Sequence[Hashable]]
550562
if len(tuples) == 0:
551563
if names is None:

pandas/tests/indexes/base_class/test_constructors.py

+8
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,11 @@ def test_constructor_cast(self):
4040
msg = "could not convert string to float"
4141
with pytest.raises(ValueError, match=msg):
4242
Index(["a", "b", "c"], dtype=float)
43+
44+
@pytest.mark.parametrize("tuple_list", [[()], [(), ()]])
45+
def test_construct_empty_tuples(self, tuple_list):
46+
# GH #45608
47+
result = Index(tuple_list)
48+
expected = MultiIndex.from_tuples(tuple_list)
49+
50+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)