From 0aaaad8c03d3be21ba97e5f3b17a0ce5d23252d4 Mon Sep 17 00:00:00 2001 From: andrejonasson Date: Sat, 26 Aug 2017 23:21:33 +0200 Subject: [PATCH] ERR: Make get_indexer return the correct indexer when Index is numeric and target is boolean (#16877) --- doc/source/whatsnew/v0.21.0.txt | 1 + pandas/core/indexes/base.py | 4 +++- pandas/tests/indexes/test_base.py | 12 ++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index fcadd26156b1d4..119c0de2fa1244 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -358,6 +358,7 @@ Indexing - Allow unicode empty strings as placeholders in multilevel columns in Python 2 (:issue:`17099`) - Bug in ``.iloc`` when used with inplace addition or assignment and an int indexer on a ``MultiIndex`` causing the wrong indexes to be read from and written to (:issue:`17148`) - Bug in ``.isin()`` in which checking membership in empty ``Series`` objects raised an error (:issue:`16991`) +- :func:`get_indexer` now returns the correct indexer when a numeric ``Index`` is passed a boolean target (:issue:`16877`) I/O ^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index a21e6df3ffc93d..8c1acf39deeccd 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2584,6 +2584,9 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): if tolerance is not None: tolerance = self._convert_tolerance(tolerance) + if target.is_boolean() and self.is_numeric(): + return np.repeat(-1, target.size) + pself, ptarget = self._maybe_promote(target) if pself is not self or ptarget is not target: return pself.get_indexer(ptarget, method=method, limit=limit, @@ -2612,7 +2615,6 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): 'backfill or nearest reindexing') indexer = self._engine.get_indexer(target._values) - return _ensure_platform_int(indexer) def _convert_tolerance(self, tolerance): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index ef36e4a91aa1c7..b9b0a776e46d44 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1131,6 +1131,18 @@ def test_get_indexer_strings(self): with pytest.raises(TypeError): idx.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=2) + def test_get_indexer_boolean_index_boolean_target(self): + boolean_idx = pd.Index([True, False]) + actual = boolean_idx.get_indexer([True, True, False]) + expected = np.array([0, 0, 1]) + tm.assert_numpy_array_equal(actual, expected, check_dtype=False) + + def test_get_indexer_numeric_index_boolean_target(self): + numeric_idx = pd.Index(range(4)) + actual = numeric_idx.get_indexer([True, False, True]) + expected = np.repeat(-1, 3) + tm.assert_numpy_array_equal(actual, expected, check_dtype=False) + def test_get_loc(self): idx = pd.Index([0, 1, 2]) all_methods = [None, 'pad', 'backfill', 'nearest']