Skip to content

Commit 54256b5

Browse files
authored
Bug in loc raised for numeric label even when label is in Index (#37675)
1 parent 5a6ed40 commit 54256b5

File tree

3 files changed

+12
-7
lines changed

3 files changed

+12
-7
lines changed

doc/source/whatsnew/v1.2.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,7 @@ Indexing
466466
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`MultiIndex` with a level named "0" (:issue:`37194`)
467467
- Bug in :meth:`Series.__getitem__` when using an unsigned integer array as an indexer giving incorrect results or segfaulting instead of raising ``KeyError`` (:issue:`37218`)
468468
- Bug in :meth:`Index.where` incorrectly casting numeric values to strings (:issue:`37591`)
469+
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` raises when numeric label was given for object :class:`Index` although label was in :class:`Index` (:issue:`26491`)
469470

470471
Missing
471472
^^^^^^^

pandas/core/indexes/base.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -5200,13 +5200,8 @@ def _maybe_cast_slice_bound(self, label, side: str_t, kind):
52005200
# We are a plain index here (sub-class override this method if they
52015201
# wish to have special treatment for floats/ints, e.g. Float64Index and
52025202
# datetimelike Indexes
5203-
# reject them
5204-
if is_float(label):
5205-
self._invalid_indexer("slice", label)
5206-
5207-
# we are trying to find integer bounds on a non-integer based index
5208-
# this is rejected (generally .loc gets you here)
5209-
elif is_integer(label):
5203+
# reject them, if index does not contain label
5204+
if (is_float(label) or is_integer(label)) and label not in self.values:
52105205
self._invalid_indexer("slice", label)
52115206

52125207
return label

pandas/tests/indexing/test_loc.py

+9
Original file line numberDiff line numberDiff line change
@@ -1868,3 +1868,12 @@ def test_loc_setitem_dt64tz_values(self):
18681868
s2["a"] = expected
18691869
result = s2["a"]
18701870
assert result == expected
1871+
1872+
1873+
@pytest.mark.parametrize("value", [1, 1.5])
1874+
def test_loc_int_in_object_index(frame_or_series, value):
1875+
# GH: 26491
1876+
obj = frame_or_series(range(4), index=[value, "first", 2, "third"])
1877+
result = obj.loc[value:"third"]
1878+
expected = frame_or_series(range(4), index=[value, "first", 2, "third"])
1879+
tm.assert_equal(result, expected)

0 commit comments

Comments
 (0)