Skip to content

BUG: pd.MultiIndex.get_loc(np.nan) #28783

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

Closed
wants to merge 1 commit into from
Closed
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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ Indexing
- Bug in reindexing a :meth:`PeriodIndex` with another type of index that contained a `Period` (:issue:`28323`) (:issue:`28337`)
- Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`)
- Bug in :meth:`Float64Index.astype` where ``np.inf`` was not handled properly when casting to an integer dtype (:issue:`28475`)
- When index is ``MultiIndex``, Using ``.get_loc`` can't find ``nan`` with a null value as input (:issue:`19132`)

Missing
^^^^^^^
Expand Down
40 changes: 24 additions & 16 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2890,6 +2890,24 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes):

return m

def search_code_location(code):
# Base on argument ``code``, search where is ``code`` in level's codes

if level > 0 or self.lexsort_depth == 0:
# Desired level is not sorted
locs = np.array(level_codes == code, dtype=bool, copy=False)
if not locs.any():
# The label is present in self.levels[level] but unused:
raise KeyError(key)
return locs

i = level_codes.searchsorted(code, side="left")
j = level_codes.searchsorted(code, side="right")
if i == j:
# The label is present in self.levels[level] but unused:
raise KeyError(key)
return slice(i, j)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you really need this nested method? Unless I'm mistaken, you can just put the code = level_index.get_loc(key) in a conditional statement.

Copy link
Contributor Author

@proost proost Oct 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@toobaz there is code = level_index.get_loc(key) after else statement. This code existed before. I just nest code and put it upper place. Because nesting it shows more clearly what code is for.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is code = level_index.get_loc(key) after else statement. This code existed before.

Yes, that's what I was referring to: this PR could have just replaced that with

if not is_list_like(key) and isna(key):
    code = -1
else:
    code = level_index.get_loc(key)

right?

Because nesting it shows more clearly what code is for.

In my (limited) experience, nested functions make code less readable, and harder to debug. If we want to isolate this code, I would prefer with a separate (better documented) function. But maybe it's a matter of taste, @jreback what's your take on this?

if isinstance(key, slice):
# handle a slice, returning a slice if we can
# otherwise a boolean indexer
Expand Down Expand Up @@ -2933,24 +2951,14 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes):
j = level_codes.searchsorted(stop, side="right")
return slice(i, j, step)

elif not is_list_like(key) and isna(key):
# missing data's location is denoted by -1
# so find missing data's location
code = -1
return search_code_location(code)
else:

code = level_index.get_loc(key)

if level > 0 or self.lexsort_depth == 0:
# Desired level is not sorted
locs = np.array(level_codes == code, dtype=bool, copy=False)
if not locs.any():
# The label is present in self.levels[level] but unused:
raise KeyError(key)
return locs

i = level_codes.searchsorted(code, side="left")
j = level_codes.searchsorted(code, side="right")
if i == j:
# The label is present in self.levels[level] but unused:
raise KeyError(key)
return slice(i, j)
return search_code_location(code)

def get_locs(self, seq):
"""
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/indexes/multi/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,26 @@ def test_timestamp_multiindex_indexer():
)
should_be = pd.Series(data=np.arange(24, len(qidx) + 24), index=qidx, name="foo")
tm.assert_series_equal(result, should_be)


def test_get_loc_with_a_missing_value():
# issue 19132
idx = MultiIndex.from_product([[np.nan, 1]] * 2)
expected = slice(0, 2, None)
assert idx.get_loc(np.nan) == expected

idx = MultiIndex.from_arrays([[np.nan, 1, 2, np.nan], [3, np.nan, np.nan, 4]])
expected = np.array([True, False, False, True])
tm.assert_numpy_array_equal(idx.get_loc(np.nan), expected)


def test_get_indexer_with_nan():
# issue 19132
idx = MultiIndex.from_arrays([[1, np.nan, 2], [3, 4, 5]])
result = idx.get_indexer([1, np.nan, 2])
expected = np.array([-1, -1, -1], dtype="int32")
tm.assert_numpy_array_equal(result.astype("int32"), expected)

result = idx.get_indexer([(np.nan, 4)])
expected = np.array([1], dtype="int32")
tm.assert_numpy_array_equal(result.astype("int32"), expected)