Skip to content

Commit 7b528c9

Browse files
BUG / CoW: ensure ser[...] (indexing with Ellipsis) returns new object (#56314)
1 parent 0d22488 commit 7b528c9

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

pandas/core/series.py

+2
Original file line numberDiff line numberDiff line change
@@ -1065,6 +1065,8 @@ def __getitem__(self, key):
10651065
key = com.apply_if_callable(key, self)
10661066

10671067
if key is Ellipsis:
1068+
if using_copy_on_write() or warn_copy_on_write():
1069+
return self.copy(deep=False)
10681070
return self
10691071

10701072
key_is_scalar = is_scalar(key)

pandas/tests/copy_view/test_indexing.py

+25
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,31 @@ def test_series_getitem_slice(backend, using_copy_on_write, warn_copy_on_write):
846846
assert s.iloc[0] == 0
847847

848848

849+
def test_series_getitem_ellipsis(using_copy_on_write, warn_copy_on_write):
850+
# Case: taking a view of a Series using Ellipsis + afterwards modifying the subset
851+
s = Series([1, 2, 3])
852+
s_orig = s.copy()
853+
854+
subset = s[...]
855+
assert np.shares_memory(get_array(subset), get_array(s))
856+
857+
with tm.assert_cow_warning(warn_copy_on_write):
858+
subset.iloc[0] = 0
859+
860+
if using_copy_on_write:
861+
assert not np.shares_memory(get_array(subset), get_array(s))
862+
863+
expected = Series([0, 2, 3])
864+
tm.assert_series_equal(subset, expected)
865+
866+
if using_copy_on_write:
867+
# original parent series is not modified (CoW)
868+
tm.assert_series_equal(s, s_orig)
869+
else:
870+
# original parent series is actually updated
871+
assert s.iloc[0] == 0
872+
873+
849874
@pytest.mark.parametrize(
850875
"indexer",
851876
[slice(0, 2), np.array([True, True, False]), np.array([0, 1])],

pandas/tests/series/indexing/test_indexing.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -101,14 +101,16 @@ def test_basic_getitem_dt64tz_values():
101101
assert result == expected
102102

103103

104-
def test_getitem_setitem_ellipsis():
104+
def test_getitem_setitem_ellipsis(using_copy_on_write, warn_copy_on_write):
105105
s = Series(np.random.default_rng(2).standard_normal(10))
106106

107107
result = s[...]
108108
tm.assert_series_equal(result, s)
109109

110-
s[...] = 5
111-
assert (result == 5).all()
110+
with tm.assert_cow_warning(warn_copy_on_write):
111+
s[...] = 5
112+
if not using_copy_on_write:
113+
assert (result == 5).all()
112114

113115

114116
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)