Skip to content

Commit 47340c3

Browse files
committed
ERR: Warn when Index is numeric and indexer is boolean (#16877)
1 parent 473a7f3 commit 47340c3

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,7 @@ Indexing
358358
- Allow unicode empty strings as placeholders in multilevel columns in Python 2 (:issue:`17099`)
359359
- 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`)
360360
- Bug in ``.isin()`` in which checking membership in empty ``Series`` objects raised an error (:issue:`16991`)
361+
- Warns when a numeric ``Index``'s ``get_indexer`` is passed a boolean indexer (:issue:`16877`)
361362

362363
I/O
363364
^^^

pandas/core/indexes/base.py

+6
Original file line numberDiff line numberDiff line change
@@ -2584,6 +2584,12 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None):
25842584
if tolerance is not None:
25852585
tolerance = self._convert_tolerance(tolerance)
25862586

2587+
if target.is_boolean() and self.is_numeric():
2588+
warnings.warn('Index is numeric and indexer is boolean, '
2589+
'possible unintended conversion from boolean '
2590+
'to numeric',
2591+
RuntimeWarning, stacklevel=1)
2592+
25872593
pself, ptarget = self._maybe_promote(target)
25882594
if pself is not self or ptarget is not target:
25892595
return pself.get_indexer(ptarget, method=method, limit=limit,

pandas/tests/indexes/test_base.py

+11
Original file line numberDiff line numberDiff line change
@@ -1131,6 +1131,17 @@ def test_get_indexer_strings(self):
11311131
with pytest.raises(TypeError):
11321132
idx.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=2)
11331133

1134+
def test_get_indexer_boolean_target(self):
1135+
boolean_idx = pd.Index([True, False])
1136+
1137+
actual = boolean_idx.get_indexer([True, True, False])
1138+
expected = np.array([0, 0, 1])
1139+
tm.assert_numpy_array_equal(actual, expected)
1140+
1141+
numeric_idx = pd.Index(range(4))
1142+
with pytest.warns(RuntimeWarning):
1143+
numeric_idx.get_indexer([True])
1144+
11341145
def test_get_loc(self):
11351146
idx = pd.Index([0, 1, 2])
11361147
all_methods = [None, 'pad', 'backfill', 'nearest']

0 commit comments

Comments
 (0)