Skip to content

Commit 1252782

Browse files
ENH: Copy inputs in PeriodIndex constructor by default (GH#63388)
1 parent 91e78da commit 1252782

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

pandas/core/indexes/period.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,13 @@
2727
set_module,
2828
)
2929

30+
from pandas.core.dtypes.astype import astype_is_view
3031
from pandas.core.dtypes.common import is_integer
3132
from pandas.core.dtypes.dtypes import PeriodDtype
3233
from pandas.core.dtypes.generic import ABCSeries
3334
from pandas.core.dtypes.missing import is_valid_na_for_dtype
3435

36+
from pandas.core.arrays import ExtensionArray
3537
from pandas.core.arrays.period import (
3638
PeriodArray,
3739
period_array,
@@ -101,8 +103,13 @@ class PeriodIndex(DatetimeIndexOpsMixin):
101103
One of pandas period strings or corresponding objects.
102104
dtype : str or PeriodDtype, default None
103105
A dtype from which to extract a freq.
104-
copy : bool
105-
Make a copy of input ndarray.
106+
copy : bool, default None
107+
Whether to copy input data, only relevant for array, Series, and Index
108+
inputs (for other input, e.g. a list, a new array is created anyway).
109+
Defaults to True for array input and False for Index/Series.
110+
Set to False to avoid copying array input at your own risk (if you
111+
know the input data won't be modified elsewhere).
112+
Set to True to force copying Series/Index input up front.
106113
name : str, default None
107114
Name of the resulting PeriodIndex.
108115
@@ -220,7 +227,7 @@ def __new__(
220227
data=None,
221228
freq=None,
222229
dtype: Dtype | None = None,
223-
copy: bool = False,
230+
copy: bool | None = None,
224231
name: Hashable | None = None,
225232
) -> Self:
226233
refs = None
@@ -231,6 +238,13 @@ def __new__(
231238

232239
freq = validate_dtype_freq(dtype, freq)
233240

241+
if isinstance(data, (ExtensionArray, np.ndarray)):
242+
# GH 63388
243+
if copy is not False:
244+
if dtype is None or astype_is_view(data.dtype, dtype):
245+
data = data.copy()
246+
copy = False
247+
234248
# PeriodIndex allow PeriodIndex(period_index, freq=different)
235249
# Let's not encourage that kind of behavior in PeriodArray.
236250

0 commit comments

Comments
 (0)