Skip to content

Commit 1f91c87

Browse files
committed
BUG: copy Index inputs to Series to preserve CoW reference tracking
1 parent 576d05f commit 1f91c87

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

pandas/core/series.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,10 +399,14 @@ def __init__(
399399
self.name = name
400400
return
401401

402-
if isinstance(data, (ExtensionArray, np.ndarray)):
402+
if isinstance(data, (ExtensionArray, np.ndarray, Index)):
403403
if copy is not False:
404404
if dtype is None or astype_is_view(data.dtype, pandas_dtype(dtype)):
405-
data = data.copy()
405+
if isinstance(data, Index):
406+
# https://github.com/pandas-dev/pandas/issues/63306#issuecomment-3637458119
407+
data = data.copy(deep=True)
408+
else:
409+
data = data.copy()
406410
if copy is None:
407411
copy = False
408412

pandas/tests/copy_view/test_constructors.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,24 @@ def test_series_from_array_different_dtype(copy):
107107
def test_series_from_index(idx):
108108
ser = Series(idx)
109109
expected = idx.copy(deep=True)
110-
assert np.shares_memory(get_array(ser), get_array(idx))
111-
assert not ser._mgr._has_no_reference(0)
110+
assert not np.shares_memory(get_array(ser), get_array(idx))
111+
assert ser._mgr._has_no_reference(0)
112112
ser.iloc[0] = ser.iloc[1]
113113
tm.assert_index_equal(idx, expected)
114114

115115

116+
def test_series_from_temporary_index_readonly_data():
117+
# GH 63306
118+
arr = np.array([0, 1])
119+
arr.flags.writeable = False
120+
ser = Series(Index(arr))
121+
assert not np.shares_memory(arr, get_array(ser))
122+
assert ser._mgr._has_no_reference(0)
123+
ser[[False, True]] = [0, 2]
124+
expected = Series([0, 2])
125+
tm.assert_series_equal(ser, expected)
126+
127+
116128
def test_series_from_index_different_dtypes():
117129
idx = Index([1, 2, 3], dtype="int64")
118130
ser = Series(idx, dtype="int32")

0 commit comments

Comments
 (0)