diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1979bde796452..3770e130e4dad 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -669,6 +669,7 @@ Indexing - Bug where indexing with a Numpy array containing negative values would mutate the indexer (:issue:`21867`) - Bug where mixed indexes wouldn't allow integers for ``.at`` (:issue:`19860`) - ``Float64Index.get_loc`` now raises ``KeyError`` when boolean key passed. (:issue:`19087`) +- Bug in :meth:`DataFrame.loc` when indexing with an :class:`IntervalIndex` (:issue:`19977`) Missing ^^^^^^^ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index a245ecfa007f3..b63f874abff85 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1491,7 +1491,7 @@ def __getitem__(self, key): try: if self._is_scalar_access(key): return self._getitem_scalar(key) - except (KeyError, IndexError): + except (KeyError, IndexError, AttributeError): pass return self._getitem_tuple(key) else: diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 6a4cf1ffc6071..f0c4d7be2f293 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -3099,6 +3099,28 @@ def test_type_error_multiindex(self): result = dg['x', 0] assert_series_equal(result, expected) + def test_interval_index(self): + # GH 19977 + index = pd.interval_range(start=0, periods=3) + df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + index=index, + columns=['A', 'B', 'C']) + + expected = 1 + result = df.loc[0.5, 'A'] + assert_almost_equal(result, expected) + + index = pd.interval_range(start=0, periods=3, closed='both') + df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + index=index, + columns=['A', 'B', 'C']) + + index_exp = pd.interval_range(start=0, periods=2, + freq=1, closed='both') + expected = pd.Series([1, 4], index=index_exp, name='A') + result = df.loc[1, 'A'] + assert_series_equal(result, expected) + class TestDataFrameIndexingDatetimeWithTZ(TestData):