Skip to content

Commit 5eb9988

Browse files
sideeyejreback
authored andcommitted
BUG: fix failing DataFrame.loc when indexing with an IntervalIndex (#22576)
1 parent 9b2e6db commit 5eb9988

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,7 @@ Indexing
712712
- Bug where indexing with a Numpy array containing negative values would mutate the indexer (:issue:`21867`)
713713
- Bug where mixed indexes wouldn't allow integers for ``.at`` (:issue:`19860`)
714714
- ``Float64Index.get_loc`` now raises ``KeyError`` when boolean key passed. (:issue:`19087`)
715+
- Bug in :meth:`DataFrame.loc` when indexing with an :class:`IntervalIndex` (:issue:`19977`)
715716

716717
Missing
717718
^^^^^^^

pandas/core/indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1491,7 +1491,7 @@ def __getitem__(self, key):
14911491
try:
14921492
if self._is_scalar_access(key):
14931493
return self._getitem_scalar(key)
1494-
except (KeyError, IndexError):
1494+
except (KeyError, IndexError, AttributeError):
14951495
pass
14961496
return self._getitem_tuple(key)
14971497
else:

pandas/tests/frame/test_indexing.py

+22
Original file line numberDiff line numberDiff line change
@@ -3099,6 +3099,28 @@ def test_type_error_multiindex(self):
30993099
result = dg['x', 0]
31003100
assert_series_equal(result, expected)
31013101

3102+
def test_interval_index(self):
3103+
# GH 19977
3104+
index = pd.interval_range(start=0, periods=3)
3105+
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
3106+
index=index,
3107+
columns=['A', 'B', 'C'])
3108+
3109+
expected = 1
3110+
result = df.loc[0.5, 'A']
3111+
assert_almost_equal(result, expected)
3112+
3113+
index = pd.interval_range(start=0, periods=3, closed='both')
3114+
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
3115+
index=index,
3116+
columns=['A', 'B', 'C'])
3117+
3118+
index_exp = pd.interval_range(start=0, periods=2,
3119+
freq=1, closed='both')
3120+
expected = pd.Series([1, 4], index=index_exp, name='A')
3121+
result = df.loc[1, 'A']
3122+
assert_series_equal(result, expected)
3123+
31023124

31033125
class TestDataFrameIndexingDatetimeWithTZ(TestData):
31043126

0 commit comments

Comments
 (0)