BUG: Handle readonly arrays in period_array
State: closed

Closes #25403

~@jbrockmendel suggested changing the def from `object[:]` to `ndarray[object]`. This unfortunately had the same runtime error about readonly buffers. So as a workaround for now (until Cython has const memoryviews), how about unsetting and then `re-setting` the writability of the input array?~

Labels:
name: Period
description: Period data type

Comments:
Ndarray[object] failing is surpsrising.  Does that break any other cython functions?
With

```diff
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index a5a50ea59..a10f8bd09 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1438,7 +1438,7 @@ cdef accessor _get_accessor_func(int code):

 @cython.wraparound(False)
 @cython.boundscheck(False)
-def extract_ordinals(object[:] values, freq):
+def extract_ordinals(ndarray[:] values, freq):
     cdef:
         Py_ssize_t i, n = len(values)
         int64_t[:] ordinals = np.empty(n, dtype=np.int64)
@@ -1472,7 +1472,7 @@ def extract_ordinals(object[:] values, freq):
     return ordinals.base  # .base to access underlying np.ndarray


-def extract_freq(object[:] values):
+def extract_freq(ndarray[:] values):
     cdef:
         Py_ssize_t i, n = len(values)
         object p
```

I see

```pytb
In [6]: pa = pd.PeriodIndex([pd.Period('2019-01-01')]).to_numpy()


In [8]: pa.setflags(write=False)

In [9]: pd.DataFrame(dict(date=pa, x=[1]))
## -- End pasted text --
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-276f30016596> in <module>
      8 pa.setflags(write=False)
      9
---> 10 pd.DataFrame(dict(date=pa, x=[1]))

~/sandbox/pandas/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    390                                  dtype=dtype, copy=copy)
    391         elif isinstance(data, dict):
--> 392             mgr = init_dict(data, index, columns, dtype=dtype)
    393         elif isinstance(data, ma.MaskedArray):
    394             import numpy.ma.mrecords as mrecords

~/sandbox/pandas/pandas/core/internals/construction.py in init_dict(data, index, columns, dtype)
    204         arrays = [data[k] if not is_datetime64tz_dtype(data[k]) else
    205                   data[k].copy(deep=True) for k in keys]
--> 206     return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
    207
    208

~/sandbox/pandas/pandas/core/internals/construction.py in arrays_to_mgr(arrays, arr_names, index, columns, dtype)
     54
     55     # don't force copy because getting jammed in an ndarray anyway
---> 56     arrays = _homogenize(arrays, index, dtype)
     57
     58     # from BlockManager perspective

~/sandbox/pandas/pandas/core/internals/construction.py in _homogenize(data, index, dtype)
    269                 val = lib.fast_multiget(val, oindex.values, default=np.nan)
    270             val = sanitize_array(val, index, dtype=dtype, copy=False,
--> 271                                  raise_cast_failure=False)
    272
    273         homogenized.append(val)

~/sandbox/pandas/pandas/core/internals/construction.py in sanitize_array(data, index, dtype, copy, raise_cast_failure)
    669         if inferred == 'period':
    670             try:
--> 671                 subarr = period_array(subarr)
    672             except IncompatibleFrequency:
    673                 pass

~/sandbox/pandas/pandas/core/arrays/period.py in period_array(data, freq, copy)
    786     data = ensure_object(data)
    787
--> 788     return PeriodArray._from_sequence(data, dtype=dtype)
    789
    790

~/sandbox/pandas/pandas/core/arrays/period.py in _from_sequence(cls, scalars, dtype, copy)
    197             periods = periods.copy()
    198
--> 199         freq = freq or libperiod.extract_freq(periods)
    200         ordinals = libperiod.extract_ordinals(periods, freq)
    201         return cls(ordinals, freq=freq)

~/sandbox/pandas/pandas/_libs/tslibs/period.pyx in pandas._libs.tslibs.period.extract_freq()
   1473
   1474
-> 1475 def extract_freq(ndarray[:] values):
   1476     cdef:
   1477         Py_ssize_t i, n = len(values)

~/sandbox/pandas/pandas/_libs/tslibs/period.cpython-37m-darwin.so in View.MemoryView.memoryview_cwrapper()

~/sandbox/pandas/pandas/_libs/tslibs/period.cpython-37m-darwin.so in View.MemoryView.memoryview.__cinit__()

ValueError: buffer source array is read-only
```
Sorry, I messed that up. Pushing a fix.
# [Codecov](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=h1) Report
> Merging [#25556](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=desc) into [master](https://codecov.io/gh/pandas-dev/pandas/commit/a54852a66f341425a83beb70cfe35a105b719794?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `100%`.

[![Impacted file tree graph](https://codecov.io/gh/pandas-dev/pandas/pull/25556/graphs/tree.svg?width=650&token=eZ4WkYLtcO&height=150&src=pr)](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master   #25556      +/-   ##
==========================================
+ Coverage   91.27%   91.27%   +<.01%     
==========================================
  Files         173      173              
  Lines       52960    52963       +3     
==========================================
+ Hits        48337    48341       +4     
+ Misses       4623     4622       -1
```

| Flag | Coverage Δ | |
|---|---|---|
| #multiple | `89.84% <100%> (ø)` | :arrow_up: |
| #single | `41.71% <100%> (-0.01%)` | :arrow_down: |

| [Impacted Files](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pandas/core/arrays/period.py](https://codecov.io/gh/pandas-dev/pandas/pull/25556/diff?src=pr&el=tree#diff-cGFuZGFzL2NvcmUvYXJyYXlzL3BlcmlvZC5weQ==) | `98.54% <100%> (+0.01%)` | :arrow_up: |
| [pandas/util/testing.py](https://codecov.io/gh/pandas-dev/pandas/pull/25556/diff?src=pr&el=tree#diff-cGFuZGFzL3V0aWwvdGVzdGluZy5weQ==) | `87.66% <0%> (+0.09%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=footer). Last update [a54852a...0dae2b3](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

# [Codecov](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=h1) Report
> Merging [#25556](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=desc) into [master](https://codecov.io/gh/pandas-dev/pandas/commit/3e652ac565e054b763ccbe23006c02704f6cd1b1?src=pr&el=desc) will **increase** coverage by `<.01%`.
> The diff coverage is `n/a`.

[![Impacted file tree graph](https://codecov.io/gh/pandas-dev/pandas/pull/25556/graphs/tree.svg?width=650&token=eZ4WkYLtcO&height=150&src=pr)](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master   #25556      +/-   ##
==========================================
+ Coverage   91.26%   91.26%   +<.01%     
==========================================
  Files         173      173              
  Lines       52966    52966              
==========================================
+ Hits        48337    48338       +1     
+ Misses       4629     4628       -1
```

| Flag | Coverage Δ | |
|---|---|---|
| #multiple | `89.83% <ø> (ø)` | :arrow_up: |
| #single | `41.71% <ø> (-0.01%)` | :arrow_down: |

| [Impacted Files](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [pandas/util/testing.py](https://codecov.io/gh/pandas-dev/pandas/pull/25556/diff?src=pr&el=tree#diff-cGFuZGFzL3V0aWwvdGVzdGluZy5weQ==) | `87.66% <0%> (+0.09%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=footer). Last update [3e652ac...128c98b](https://codecov.io/gh/pandas-dev/pandas/pull/25556?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).