Skip to content

Commit 3517cc2

Browse files
committed
BUG: pd.MultiIndex.get_loc(np.nan) (#19132)
MultiIndex.get_loc can find nan when input is NA value(e.g. nan, None)
1 parent d5fa16b commit 3517cc2

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ Indexing
229229
- Bug in reindexing a :meth:`PeriodIndex` with another type of index that contained a `Period` (:issue:`28323`) (:issue:`28337`)
230230
- Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`)
231231
- Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`)
232+
- Bug in :meth:`MultiIndex.get_loc` can't find ``np.nan`` when input is NA value (:issue:`19132`)
232233

233234
Missing
234235
^^^^^^^

pandas/core/indexes/multi.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -2934,8 +2934,12 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes):
29342934
return slice(i, j, step)
29352935

29362936
else:
2937-
2938-
code = level_index.get_loc(key)
2937+
if not is_list_like(key) and isna(key):
2938+
# missing data's location is considered as -1
2939+
# so find missing data's location
2940+
code = -1
2941+
else:
2942+
code = level_index.get_loc(key)
29392943

29402944
if level > 0 or self.lexsort_depth == 0:
29412945
# Desired level is not sorted

pandas/tests/indexes/multi/test_indexing.py

+11
Original file line numberDiff line numberDiff line change
@@ -439,3 +439,14 @@ def test_timestamp_multiindex_indexer():
439439
)
440440
should_be = pd.Series(data=np.arange(24, len(qidx) + 24), index=qidx, name="foo")
441441
tm.assert_series_equal(result, should_be)
442+
443+
444+
def test_get_loc_missing_value():
445+
# issue 19132
446+
idx = MultiIndex.from_product([[np.nan, 1]] * 2)
447+
expected = slice(0, 2, None)
448+
assert idx.get_loc(np.nan) == expected
449+
450+
idx = MultiIndex.from_arrays([[np.nan, 1, 2, np.nan]])
451+
expected = np.array([True, False, False, True])
452+
tm.assert_numpy_array_equal(idx.get_loc(np.nan), expected)

0 commit comments

Comments
 (0)