Skip to content

Commit 4f7c50d

Browse files
authored
BUG: ser.loc[range] = foo treating key as positional (#45479)
1 parent 3aa2ed4 commit 4f7c50d

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ Indexing
261261
- Bug in :meth:`DataFrame.iloc` where indexing a single row on a :class:`DataFrame` with a single ExtensionDtype column gave a copy instead of a view on the underlying data (:issue:`45241`)
262262
- Bug in :meth:`Series.__setitem__` with a non-integer :class:`Index` when using an integer key to set a value that cannot be set inplace where a ``ValueError`` was raised insead of casting to a common dtype (:issue:`45070`)
263263
- Bug when setting a value too large for a :class:`Series` dtype failing to coerce to a common type (:issue:`26049`, :issue:`32878`)
264+
- Bug in :meth:`loc.__setitem__` treating ``range`` keys as positional instead of label-based (:issue:`45479`)
264265
- Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`)
265266
- Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtpye :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`)
266267
- Bug in getting a column from a DataFrame with an object-dtype row index with datetime-like values: the resulting Series now preserves the exact object-dtype Index from the parent DataFrame (:issue:`42950`)

pandas/core/indexing.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,8 @@ def _get_setitem_indexer(self, key):
665665
return self._convert_tuple(key)
666666

667667
if isinstance(key, range):
668-
return list(key)
668+
# GH#45479 test_loc_setitem_range_key
669+
key = list(key)
669670

670671
return self._convert_to_indexer(key, axis=0)
671672

pandas/tests/indexing/test_loc.py

+13
Original file line numberDiff line numberDiff line change
@@ -1555,6 +1555,19 @@ def test_loc_setitem_cast3(self):
15551555
df.one = np.int8(7)
15561556
assert df.dtypes.one == np.dtype(np.int8)
15571557

1558+
def test_loc_setitem_range_key(self, frame_or_series):
1559+
# GH#45479 don't treat range key as positional
1560+
obj = frame_or_series(range(5), index=[3, 4, 1, 0, 2])
1561+
1562+
values = [9, 10, 11]
1563+
if obj.ndim == 2:
1564+
values = [[9], [10], [11]]
1565+
1566+
obj.loc[range(3)] = values
1567+
1568+
expected = frame_or_series([0, 1, 10, 9, 11], index=obj.index)
1569+
tm.assert_equal(obj, expected)
1570+
15581571

15591572
class TestLocWithEllipsis:
15601573
@pytest.fixture(params=[tm.loc, tm.iloc])

0 commit comments

Comments
 (0)