Skip to content

Commit a607872

Browse files
authored
BUG: Regression in .loc accepting a boolean Index as an indexer (#17738)
closes #17131
1 parent 2781b18 commit a607872

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,7 @@ Indexing
668668
- Bug in ``IntervalIndex`` where performing a scalar lookup fails for included right endpoints of non-overlapping monotonic decreasing indexes (:issue:`16417`, :issue:`17271`)
669669
- Bug in :meth:`DataFrame.first_valid_index` and :meth:`DataFrame.last_valid_index` when no valid entry (:issue:`17400`)
670670
- Bug in :func:`Series.rename` when called with a `callable`, incorrectly alters the name of the `Series`, rather than the name of the `Index`. (:issue:`17407`)
671+
- Regression in ``.loc`` accepting a boolean ``Index`` as an indexer (:issue:`17131`)
671672

672673
I/O
673674
^^^

pandas/core/common.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from pandas import compat
1616
from pandas.compat import long, zip, iteritems
1717
from pandas.core.config import get_option
18-
from pandas.core.dtypes.generic import ABCSeries
18+
from pandas.core.dtypes.generic import ABCSeries, ABCIndex
1919
from pandas.core.dtypes.common import _NS_DTYPE
2020
from pandas.core.dtypes.inference import _iterable_not_string
2121
from pandas.core.dtypes.missing import isna, isnull, notnull # noqa
@@ -182,7 +182,7 @@ def _maybe_box_datetimelike(value):
182182

183183

184184
def is_bool_indexer(key):
185-
if isinstance(key, (ABCSeries, np.ndarray)):
185+
if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)):
186186
if key.dtype == np.object_:
187187
key = np.asarray(_values_from_object(key))
188188

pandas/tests/indexing/test_loc.py

+17
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,23 @@ def test_loc_getitem_label_slice(self):
317317
self.check_result('mixed slice', 'loc', slice(2, 4, 2), 'ix', slice(
318318
2, 4, 2), typs=['mixed'], axes=0, fails=TypeError)
319319

320+
def test_loc_index(self):
321+
# gh-17131
322+
# a boolean index should index like a boolean numpy array
323+
324+
df = DataFrame(
325+
np.random.random(size=(5, 10)),
326+
index=["alpha_0", "alpha_1", "alpha_2", "beta_0", "beta_1"])
327+
328+
mask = df.index.map(lambda x: "alpha" in x)
329+
expected = df.loc[np.array(mask)]
330+
331+
result = df.loc[mask]
332+
tm.assert_frame_equal(result, expected)
333+
334+
result = df.loc[mask.values]
335+
tm.assert_frame_equal(result, expected)
336+
320337
def test_loc_general(self):
321338

322339
df = DataFrame(

0 commit comments

Comments
 (0)