Skip to content

Commit cded237

Browse files
Backport PR #37221: Fix regression for is_monotonic_increasing with nan in MultiIndex (#37446)
Co-authored-by: patrick <61934744+phofl@users.noreply.github.com>
1 parent f87111f commit cded237

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v1.1.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Fixed regressions
2525
- Fixed regression where slicing :class:`DatetimeIndex` raised :exc:`AssertionError` on irregular time series with ``pd.NaT`` or on unsorted indices (:issue:`36953` and :issue:`35509`)
2626
- Fixed regression in certain offsets (:meth:`pd.offsets.Day() <pandas.tseries.offsets.Day>` and below) no longer being hashable (:issue:`37267`)
2727
- Fixed regression in :class:`StataReader` which required ``chunksize`` to be manually set when using an iterator to read a dataset (:issue:`37280`)
28+
- Fixed regression in :attr:`MultiIndex.is_monotonic_increasing` returning wrong results with ``NaN`` in at least one of the levels (:issue:`37220`)
2829

2930
.. ---------------------------------------------------------------------------
3031

pandas/core/indexes/multi.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1454,7 +1454,10 @@ def is_monotonic_increasing(self) -> bool:
14541454
return if the index is monotonic increasing (only equal or
14551455
increasing) values.
14561456
"""
1457-
if all(x.is_monotonic for x in self.levels):
1457+
if any(-1 in code for code in self.codes):
1458+
return False
1459+
1460+
if all(level.is_monotonic for level in self.levels):
14581461
# If each level is sorted, we can operate on the codes directly. GH27495
14591462
return libalgos.is_lexsorted(
14601463
[x.astype("int64", copy=False) for x in self.codes]

pandas/tests/indexes/multi/test_monotonic.py

+12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import pytest
23

34
import pandas as pd
45
from pandas import Index, MultiIndex
@@ -174,3 +175,14 @@ def test_is_strictly_monotonic_decreasing():
174175
)
175176
assert idx.is_monotonic_decreasing is True
176177
assert idx._is_strictly_monotonic_decreasing is False
178+
179+
180+
@pytest.mark.parametrize("attr", ["is_monotonic_increasing", "is_monotonic_decreasing"])
181+
@pytest.mark.parametrize(
182+
"values",
183+
[[(np.nan,), (1,), (2,)], [(1,), (np.nan,), (2,)], [(1,), (2,), (np.nan,)]],
184+
)
185+
def test_is_monotonic_with_nans(values, attr):
186+
# GH: 37220
187+
idx = pd.MultiIndex.from_tuples(values, names=["test"])
188+
assert getattr(idx, attr) is False

0 commit comments

Comments
 (0)