Skip to content

BUG: CategoricalIndex.get_indexer issue with NaNs (#45361) #45373

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 15 commits into from
Jan 28, 2022
Merged
Show file tree
Hide file tree
Changes from 7 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
11 changes: 10 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3696,6 +3696,7 @@ def get_indexer(
tolerance=None,
) -> npt.NDArray[np.intp]:
method = missing.clean_reindex_fill_method(method)
orig_target = target
target = self._maybe_cast_listlike_indexer(target)

self._check_indexing_method(method, limit, tolerance)
Expand All @@ -3718,9 +3719,17 @@ def get_indexer(

indexer = self._engine.get_indexer(target.codes)
if self.hasnans and target.hasnans:
# After _maybe_cast_listlike_indexer, target elements which do not
# belong to some category are changed to NaNs
# Mask to track actual NaN values compared to inserted NaN values
try:
target_nans = isna(orig_target)
except NotImplementedError:
target_nans = False
loc = self.get_loc(np.nan)
mask = target.isna()
indexer[mask] = loc
indexer[target_nans] = loc
indexer[mask & ~target_nans] = -1
return indexer

if is_categorical_dtype(target.dtype):
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/indexes/categorical/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,18 @@ def test_get_indexer_same_categories_different_order(self):
expected = np.array([1, 1], dtype="intp")
tm.assert_numpy_array_equal(result, expected)

def test_get_indexer_nans_in_index_and_target(self):
# GH 45361
ci = CategoricalIndex([1, 2, np.nan, 3])
other1 = [2, 3, 4, np.nan]
other2 = [1, 4, 2, 3]
res1 = ci.get_indexer(other1)
res2 = ci.get_indexer(other2)
expected1 = np.array([1, 3, -1, 2], dtype=np.intp)
expected2 = np.array([0, -1, 1, 3], dtype=np.intp)
tm.assert_numpy_array_equal(res1, expected1)
tm.assert_numpy_array_equal(res2, expected2)


class TestWhere:
def test_where(self, listlike_box):
Expand Down