Skip to content
14 changes: 10 additions & 4 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def __new__(
cls,
data=None,
dtype=None,
copy: bool = False,
copy: bool | None = None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also use the updated description in the Series docstring as a starting point to update the docstring here as well (as the end goal should be to make it similar)

name=None,
tupleize_cols: bool = True,
) -> Self:
Expand All @@ -501,7 +501,7 @@ def __new__(

# range
if isinstance(data, (range, RangeIndex)):
result = RangeIndex(start=data, copy=copy, name=name)
result = RangeIndex(start=data, copy=bool(copy), name=name)
if dtype is not None:
return result.astype(dtype, copy=False)
# error: Incompatible return value type (got "MultiIndex",
Expand All @@ -517,7 +517,13 @@ def __new__(
pass

elif isinstance(data, (np.ndarray, ABCMultiIndex)):
if isinstance(data, ABCMultiIndex):
if isinstance(data, np.ndarray):
if copy is not False:
if dtype is None or astype_is_view(data.dtype, pandas_dtype(dtype)):
# GH 63306
data = data.copy()
copy = False
elif isinstance(data, ABCMultiIndex):
data = data._values

if data.dtype.kind not in "iufcbmM":
Expand Down Expand Up @@ -569,7 +575,7 @@ def __new__(
data = com.asarray_tuplesafe(data, dtype=_dtype_obj)

try:
arr = sanitize_array(data, None, dtype=dtype, copy=copy)
arr = sanitize_array(data, None, dtype=dtype, copy=bool(copy))
except ValueError as err:
if "index must be specified when data is not list-like" in str(err):
raise cls._raise_scalar_data_error(data) from err
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/copy_view/index/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,21 @@ def test_index_values():
idx = Index([1, 2, 3])
result = idx.values
assert result.flags.writeable is False


def test_constructor_copy_input_ndarray_default():
arr = np.array([0, 1])
idx = Index(arr)
assert not np.shares_memory(arr, get_array(idx))


def test_series_from_temporary_index_readonly_data():
# GH 63370
arr = np.array([0, 1], dtype=np.dtype(np.int8))
arr.flags.writeable = False
ser = Series(Index(arr))
assert not np.shares_memory(arr, get_array(ser))
assert ser._mgr._has_no_reference(0)
ser[[False, True]] = np.array([0, 2], dtype=np.dtype(np.int8))
expected = Series([0, 2], dtype=np.dtype(np.int8))
tm.assert_series_equal(ser, expected)
Loading