Skip to content

BUG: MultiIndex comparison with tuple #21517 #37170

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

Merged
merged 5 commits into from
Oct 18, 2020
Merged
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ Numeric
- Bug in :meth:`DataFrame.__rmatmul__` error handling reporting transposed shapes (:issue:`21581`)
- Bug in :class:`Series` flex arithmetic methods where the result when operating with a ``list``, ``tuple`` or ``np.ndarray`` would have an incorrect name (:issue:`36760`)
- Bug in :class:`IntegerArray` multiplication with ``timedelta`` and ``np.timedelta64`` objects (:issue:`36870`)
- Bug in :class:`MultiIndex` comparison with tuple incorrectly treating tuple as array-like (:issue:`21517`)
- Bug in :meth:`DataFrame.diff` with ``datetime64`` dtypes including ``NaT`` values failing to fill ``NaT`` results correctly (:issue:`32441`)
- Bug in :class:`DataFrame` arithmetic ops incorrectly accepting keyword arguments (:issue:`36843`)
- Bug in :class:`IntervalArray` comparisons with :class:`Series` not returning :class:`Series` (:issue:`36908`)
Expand Down
16 changes: 9 additions & 7 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.generic import (
ABCCategorical,
ABCDatetimeIndex,
ABCMultiIndex,
ABCPandasArray,
Expand All @@ -83,6 +82,7 @@
from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype
from pandas.core.base import IndexOpsMixin, PandasObject
import pandas.core.common as com
from pandas.core.construction import extract_array
from pandas.core.indexers import deprecate_ndim_indexing
from pandas.core.indexes.frozen import FrozenList
from pandas.core.ops import get_op_result_name
Expand Down Expand Up @@ -5376,11 +5376,13 @@ def _cmp_method(self, other, op):
if len(self) != len(other):
raise ValueError("Lengths must match to compare")

if is_object_dtype(self.dtype) and isinstance(other, ABCCategorical):
left = type(other)(self._values, dtype=other.dtype)
return op(left, other)
elif is_object_dtype(self.dtype) and isinstance(other, ExtensionArray):
# e.g. PeriodArray
if not isinstance(other, ABCMultiIndex):
other = extract_array(other, extract_numpy=True)
else:
other = np.asarray(other)

if is_object_dtype(self.dtype) and isinstance(other, ExtensionArray):
# e.g. PeriodArray, Categorical
with np.errstate(all="ignore"):
result = op(self._values, other)

Expand All @@ -5395,7 +5397,7 @@ def _cmp_method(self, other, op):

else:
with np.errstate(all="ignore"):
result = ops.comparison_op(self._values, np.asarray(other), op)
result = ops.comparison_op(self._values, other, op)

return result

Expand Down
40 changes: 40 additions & 0 deletions pandas/tests/indexes/multi/test_equivalence.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,46 @@ def test_equals_op(idx):
tm.assert_series_equal(series_a == item, Series(expected3))


def test_compare_tuple():
# GH#21517
mi = MultiIndex.from_product([[1, 2]] * 2)

all_false = np.array([False, False, False, False])

result = mi == mi[0]
expected = np.array([True, False, False, False])
tm.assert_numpy_array_equal(result, expected)

result = mi != mi[0]
tm.assert_numpy_array_equal(result, ~expected)

result = mi < mi[0]
tm.assert_numpy_array_equal(result, all_false)

result = mi <= mi[0]
tm.assert_numpy_array_equal(result, expected)

result = mi > mi[0]
tm.assert_numpy_array_equal(result, ~expected)

result = mi >= mi[0]
tm.assert_numpy_array_equal(result, ~all_false)


def test_compare_tuple_strs():
# GH#34180

mi = MultiIndex.from_tuples([("a", "b"), ("b", "c"), ("c", "a")])

result = mi == ("c", "a")
expected = np.array([False, False, True])
tm.assert_numpy_array_equal(result, expected)

result = mi == ("c",)
expected = np.array([False, False, False])
tm.assert_numpy_array_equal(result, expected)


def test_equals_multi(idx):
assert idx.equals(idx)
assert not idx.equals(idx.values)
Expand Down