Skip to content

Commit 9221e5a

Browse files
ENH: Copy inputs in TimedeltaIndex constructor by default (GH#63388)
1 parent f59ab9e commit 9221e5a

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

pandas/core/indexes/timedeltas.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
cast,
88
)
99

10+
import numpy as np
11+
1012
from pandas._libs import (
1113
index as libindex,
1214
lib,
@@ -23,9 +25,11 @@
2325
is_scalar,
2426
pandas_dtype,
2527
)
28+
from pandas.core.dtypes.astype import astype_is_view
2629
from pandas.core.dtypes.dtypes import ArrowDtype
2730
from pandas.core.dtypes.generic import ABCSeries
2831

32+
from pandas.core.arrays import ExtensionArray
2933
from pandas.core.arrays.timedeltas import TimedeltaArray
3034
import pandas.core.common as com
3135
from pandas.core.indexes.base import (
@@ -81,8 +85,13 @@ class TimedeltaIndex(DatetimeTimedeltaMixin):
8185
dtype : numpy.dtype or str, default None
8286
Valid ``numpy`` dtypes are ``timedelta64[ns]``, ``timedelta64[us]``,
8387
``timedelta64[ms]``, and ``timedelta64[s]``.
84-
copy : bool
85-
Make a copy of input array.
88+
copy : bool, default None
89+
Whether to copy input data, only relevant for array, Series, and Index
90+
inputs (for other input, e.g. a list, a new array is created anyway).
91+
Defaults to True for array input and False for Index/Series.
92+
Set to False to avoid copying array input at your own risk (if you
93+
know the input data won't be modified elsewhere).
94+
Set to True to force copying Series/Index input up front.
8695
name : object
8796
Name to be stored in the index.
8897
@@ -158,11 +167,18 @@ def __new__(
158167
data=None,
159168
freq=lib.no_default,
160169
dtype=None,
161-
copy: bool = False,
170+
copy: bool | None = None,
162171
name=None,
163172
):
164173
name = maybe_extract_name(name, data, cls)
165174

175+
if isinstance(data, (ExtensionArray, np.ndarray)):
176+
# GH 63388
177+
if copy is not False:
178+
if dtype is None or astype_is_view(data.dtype, dtype):
179+
data = data.copy()
180+
copy = False
181+
166182
if is_scalar(data):
167183
cls._raise_scalar_data_error(data)
168184

0 commit comments

Comments
 (0)