Skip to content

Commit 2272ef4

Browse files
KalyanGokhalejorisvandenbossche
authored andcommitted
CLN: Comparison methods for MultiIndex should have consistent behaviour for all nlevels (GH21149) (#21195)
(cherry picked from commit a8738ba)
1 parent 14e5f3d commit 2272ef4

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v0.23.2.txt

+1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ Bug Fixes
5252
**Indexing**
5353

5454
- Bug in :meth:`Index.get_indexer_non_unique` with categorical key (:issue:`21448`)
55+
- Bug in comparison operations for :class:`MultiIndex` where error was raised on equality / inequality comparison involving a MultiIndex with ``nlevels == 1`` (:issue:`21149`)
5556
-
5657

5758
**I/O**

pandas/core/indexes/base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ def cmp_method(self, other):
9797
if needs_i8_conversion(self) and needs_i8_conversion(other):
9898
return self._evaluate_compare(other, op)
9999

100-
if is_object_dtype(self) and self.nlevels == 1:
100+
from .multi import MultiIndex
101+
if is_object_dtype(self) and not isinstance(self, MultiIndex):
101102
# don't pass MultiIndex
102103
with np.errstate(all='ignore'):
103104
result = ops._comp_method_OBJECT_ARRAY(op, self.values, other)

pandas/tests/indexes/test_multi.py

+17
Original file line numberDiff line numberDiff line change
@@ -3295,3 +3295,20 @@ def test_duplicate_multiindex_labels(self):
32953295
with pytest.raises(ValueError):
32963296
ind.set_levels([['A', 'B', 'A', 'A', 'B'], [2, 1, 3, -2, 5]],
32973297
inplace=True)
3298+
3299+
def test_multiindex_compare(self):
3300+
# GH 21149
3301+
# Ensure comparison operations for MultiIndex with nlevels == 1
3302+
# behave consistently with those for MultiIndex with nlevels > 1
3303+
3304+
midx = pd.MultiIndex.from_product([[0, 1]])
3305+
3306+
# Equality self-test: MultiIndex object vs self
3307+
expected = pd.Series([True, True])
3308+
result = pd.Series(midx == midx)
3309+
tm.assert_series_equal(result, expected)
3310+
3311+
# Greater than comparison: MultiIndex object vs self
3312+
expected = pd.Series([False, False])
3313+
result = pd.Series(midx > midx)
3314+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)