From 1d6370169ff7259fbab69f7a14460300217e371d Mon Sep 17 00:00:00 2001 From: Jeff Reback Date: Mon, 2 Oct 2017 06:30:28 -0400 Subject: [PATCH] BUG: Regression in .loc accepting a boolean Index as an indexer closes #17131 --- doc/source/whatsnew/v0.21.0.txt | 1 + pandas/core/common.py | 4 ++-- pandas/tests/indexing/test_loc.py | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index c8a0a6bff5cc7..23ff7cb9f34d4 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -667,6 +667,7 @@ Indexing - Bug in ``IntervalIndex`` where performing a scalar lookup fails for included right endpoints of non-overlapping monotonic decreasing indexes (:issue:`16417`, :issue:`17271`) - Bug in :meth:`DataFrame.first_valid_index` and :meth:`DataFrame.last_valid_index` when no valid entry (:issue:`17400`) - 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`) +- Regression in ``.loc`` accepting a boolean ``Index`` as an indexer (:issue:`17131`) I/O ^^^ diff --git a/pandas/core/common.py b/pandas/core/common.py index 0f7b86f5e74a0..2686ad370e1ed 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -15,7 +15,7 @@ from pandas import compat from pandas.compat import long, zip, iteritems from pandas.core.config import get_option -from pandas.core.dtypes.generic import ABCSeries +from pandas.core.dtypes.generic import ABCSeries, ABCIndex from pandas.core.dtypes.common import _NS_DTYPE from pandas.core.dtypes.inference import _iterable_not_string from pandas.core.dtypes.missing import isna, isnull, notnull # noqa @@ -182,7 +182,7 @@ def _maybe_box_datetimelike(value): def is_bool_indexer(key): - if isinstance(key, (ABCSeries, np.ndarray)): + if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)): if key.dtype == np.object_: key = np.asarray(_values_from_object(key)) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 17316a714e260..95d6a24e68425 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -317,6 +317,23 @@ def test_loc_getitem_label_slice(self): self.check_result('mixed slice', 'loc', slice(2, 4, 2), 'ix', slice( 2, 4, 2), typs=['mixed'], axes=0, fails=TypeError) + def test_loc_index(self): + # gh-17131 + # a boolean index should index like a boolean numpy array + + df = DataFrame( + np.random.random(size=(5, 10)), + index=["alpha_0", "alpha_1", "alpha_2", "beta_0", "beta_1"]) + + mask = df.index.map(lambda x: "alpha" in x) + expected = df.loc[np.array(mask)] + + result = df.loc[mask] + tm.assert_frame_equal(result, expected) + + result = df.loc[mask.values] + tm.assert_frame_equal(result, expected) + def test_loc_general(self): df = DataFrame(