Skip to content

Commit d967aef

Browse files
charlesdong1991jreback
authored andcommitted
BUG/TST: PeriodArray.__setitem__ with slice and list-like value (#23991)
1 parent 5259e33 commit d967aef

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

doc/source/whatsnew/v0.24.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1401,6 +1401,7 @@ Indexing
14011401
- Bug where setting a timedelta column by ``Index`` causes it to be casted to double, and therefore lose precision (:issue:`23511`)
14021402
- Bug in :func:`Index.union` and :func:`Index.intersection` where name of the ``Index`` of the result was not computed correctly for certain cases (:issue:`9943`, :issue:`9862`)
14031403
- Bug in :class:`Index` slicing with boolean :class:`Index` may raise ``TypeError`` (:issue:`22533`)
1404+
- Bug in ``PeriodArray.__setitem__`` when accepting slice and list-like value (:issue:`23978`)
14041405

14051406
Missing
14061407
^^^^^^^

pandas/core/arrays/period.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ def __repr__(self):
346346

347347
def __setitem__(
348348
self,
349-
key, # type: Union[int, Sequence[int], Sequence[bool]]
349+
key, # type: Union[int, Sequence[int], Sequence[bool], slice]
350350
value # type: Union[NaTType, Period, Sequence[Period]]
351351
):
352352
# type: (...) -> None
@@ -356,11 +356,14 @@ def __setitem__(
356356
# ndarray[datetime64ns]. I think ndarray[int] / ndarray[str] won't
357357
# work, since the freq can't be inferred.
358358
if is_list_like(value):
359-
if len(key) != len(value) and not com.is_bool_indexer(key):
359+
is_slice = isinstance(key, slice)
360+
if (not is_slice
361+
and len(key) != len(value)
362+
and not com.is_bool_indexer(key)):
360363
msg = ("shape mismatch: value array of length '{}' does not "
361364
"match indexing result of length '{}'.")
362365
raise ValueError(msg.format(len(key), len(value)))
363-
if len(key) == 0:
366+
if not is_slice and len(key) == 0:
364367
return
365368

366369
value = period_array(value)

pandas/tests/extension/base/setitem.py

+10
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,13 @@ def test_setitem_tuple_index(self, data):
173173
expected = pd.Series(data.take([1, 1]), index=s.index)
174174
s[(0, 1)] = data[1]
175175
self.assert_series_equal(s, expected)
176+
177+
def test_setitem_slice_mismatch_length_raises(self, data):
178+
arr = data[:5]
179+
with pytest.raises(ValueError):
180+
arr[:1] = arr[:2]
181+
182+
def test_setitem_slice_array(self, data):
183+
arr = data[:5].copy()
184+
arr[:5] = data[-5:]
185+
self.assert_extension_array_equal(arr, data[-5:])

0 commit comments

Comments
 (0)