diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 5f79accc5c679..0c94af00c3874 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -1036,6 +1036,7 @@ Indexing - :meth:`MultiIndex.get_loc` can't find missing values when input includes missing values (:issue:`19132`) - Bug in :meth:`Series.__setitem__` incorrectly assigning values with boolean indexer when the length of new data matches the number of ``True`` values and new data is not a ``Series`` or an ``np.array`` (:issue:`30567`) - Bug in indexing with a :class:`PeriodIndex` incorrectly accepting integers representing years, use e.g. ``ser.loc["2007"]`` instead of ``ser.loc[2007]`` (:issue:`30763`) +- Bug in :meth:`DataFrame.loc.__setitem__` and :meth:`Series.loc.__setitem__` not raising error when given integer slice does not exist in index (:issue:`26412`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index ca929b188dc33..57ab60d292771 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2922,6 +2922,9 @@ def is_int(v): self._validate_indexer("slice", key.step, kind), ) + if kind == "loc" and not is_null_slicer: + return self.slice_indexer(key.start, key.stop, key.step, kind=kind) + # convert the slice to an indexer here # if we are mixed and have integers diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index a36078b11c663..21dc015b17f4f 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -915,8 +915,8 @@ def test_loc_setitem_empty_append_raises(self): with pytest.raises(KeyError, match=msg): df.loc[[0, 1], "x"] = data - msg = "cannot copy sequence with size 2 to array axis with dimension 0" - with pytest.raises(ValueError, match=msg): + msg = "cannot do slice indexing on .* with these indexers" + with pytest.raises(TypeError, match=msg): df.loc[0:2, "x"] = data def test_indexing_zerodim_np_array(self): @@ -985,6 +985,19 @@ def test_loc_setitem_float_intindex(): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize("test_series", [False, True]) +def test_loc_setitem_missing_integer_slice(test_series): + # GH 26412 + df = DataFrame({"col1": [1, 2, 3]}, index=["a", "b", "c"]) + msg = "cannot do slice indexing on .* with these indexers" + with pytest.raises(TypeError, match=msg): + if test_series: + s = df["col1"] + s.loc[0:2] = 10 + else: + df.loc[0:2] = 10 + + def test_loc_axis_1_slice(): # GH 10586 cols = [(yr, m) for yr in [2014, 2015] for m in [7, 8, 9, 10]]