Skip to content

Commit 0dae2b3

Browse files
committed
BUG: Handle readonly arrays in period_array
Closes pandas-dev#25403
1 parent a54852a commit 0dae2b3

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

doc/source/whatsnew/v0.24.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Fixed Regressions
3030
- Fixed regression in subtraction between :class:`Series` objects with ``datetime64[ns]`` dtype incorrectly raising ``OverflowError`` when the `Series` on the right contains null values (:issue:`25317`)
3131
- Fixed regression in :class:`TimedeltaIndex` where `np.sum(index)` incorrectly returned a zero-dimensional object instead of a scalar (:issue:`25282`)
3232
- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
33+
- Fixed regression in creating a period-dtype array from a read-only NumPy array of period objects. (:issue:`25403`)
3334

3435
- Fixed regression in :class:`Categorical`, where constructing it from a categorical ``Series`` and an explicit ``categories=`` that differed from that in the ``Series`` created an invalid object which could trigger segfaults. (:issue:`25318`)
3536

pandas/core/arrays/period.py

+6
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,14 @@ def _from_sequence(cls, scalars, dtype=None, copy=False):
196196
if copy:
197197
periods = periods.copy()
198198

199+
# Support readonly `scalars`.
200+
# TODO: remove flag unsetting / setting once Cython supports
201+
# const object.
202+
writeable = periods.flags.writeable
203+
periods.setflags(write=True)
199204
freq = freq or libperiod.extract_freq(periods)
200205
ordinals = libperiod.extract_ordinals(periods, freq)
206+
periods.setflags(write=writeable)
201207
return cls(ordinals, freq=freq)
202208

203209
@classmethod

pandas/tests/arrays/test_period.py

+16
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,22 @@ def test_period_array_ok(data, freq, expected):
4141
tm.assert_numpy_array_equal(result, expected)
4242

4343

44+
def test_period_array_readonly_object():
45+
# https://github.com/pandas-dev/pandas/issues/25403
46+
pa = period_array([pd.Period('2019-01-01')])
47+
arr = np.asarray(pa, dtype='object')
48+
arr.setflags(write=False)
49+
50+
result = period_array(arr)
51+
tm.assert_period_array_equal(result, pa)
52+
53+
result = pd.Series(arr)
54+
tm.assert_series_equal(result, pd.Series(pa))
55+
56+
result = pd.DataFrame({"A": arr})
57+
tm.assert_frame_equal(result, pd.DataFrame({"A": pa}))
58+
59+
4460
def test_from_datetime64_freq_changes():
4561
# https://github.com/pandas-dev/pandas/issues/23438
4662
arr = pd.date_range("2017", periods=3, freq="D")

0 commit comments

Comments
 (0)