Skip to content

Commit 4caaf95

Browse files
jbrockmendelmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#31515: REGR: DataFrame.__setitem__(slice, val) is positional
1 parent 78b7079 commit 4caaf95

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v1.0.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ Interval
7676

7777
Indexing
7878
^^^^^^^^
79-
79+
- Fixed regression in :class:`DataFrame` setting values with a slice (e.g. ``df[-4:] = 1``) indexing by label instead of position (:issue:`31469`)
8080
-
8181
-
8282
- Bug where assigning to a :class:`Series` using a IntegerArray / BooleanArray as a mask would raise ``TypeError`` (:issue:`31446`)

pandas/core/frame.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -2938,8 +2938,11 @@ def __setitem__(self, key, value):
29382938
self._set_item(key, value)
29392939

29402940
def _setitem_slice(self, key, value):
2941+
# NB: we can't just use self.loc[key] = value because that
2942+
# operates on labels and we need to operate positional for
2943+
# backwards-compat, xref GH#31469
29412944
self._check_setitem_copy()
2942-
self.loc[key] = value
2945+
self.loc._setitem_with_indexer(key, value)
29432946

29442947
def _setitem_array(self, key, value):
29452948
# also raises Exception if object array with NA values

pandas/tests/frame/indexing/test_indexing.py

+9
Original file line numberDiff line numberDiff line change
@@ -860,6 +860,15 @@ def test_fancy_getitem_slice_mixed(self, float_frame, float_string_frame):
860860

861861
assert (float_frame["C"] == 4).all()
862862

863+
def test_setitem_slice_position(self):
864+
# GH#31469
865+
df = pd.DataFrame(np.zeros((100, 1)))
866+
df[-4:] = 1
867+
arr = np.zeros((100, 1))
868+
arr[-4:] = 1
869+
expected = pd.DataFrame(arr)
870+
tm.assert_frame_equal(df, expected)
871+
863872
def test_getitem_setitem_non_ix_labels(self):
864873
df = tm.makeTimeDataFrame()
865874

0 commit comments

Comments
 (0)