Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG / CoW: ensure ser[...] (indexing with Ellipsis) returns new object #56314

Merged
merged 2 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,8 @@ def __getitem__(self, key):
key = com.apply_if_callable(key, self)

if key is Ellipsis:
if using_copy_on_write() or warn_copy_on_write():
return self.copy(deep=False)
return self

key_is_scalar = is_scalar(key)
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/copy_view/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,31 @@ def test_series_getitem_slice(backend, using_copy_on_write, warn_copy_on_write):
assert s.iloc[0] == 0


def test_series_getitem_ellipsis(using_copy_on_write, warn_copy_on_write):
# Case: taking a view of a Series using Ellipsis + afterwards modifying the subset
s = Series([1, 2, 3])
s_orig = s.copy()

subset = s[...]
assert np.shares_memory(get_array(subset), get_array(s))

with tm.assert_cow_warning(warn_copy_on_write):
subset.iloc[0] = 0

if using_copy_on_write:
assert not np.shares_memory(get_array(subset), get_array(s))

expected = Series([0, 2, 3])
tm.assert_series_equal(subset, expected)

if using_copy_on_write:
# original parent series is not modified (CoW)
tm.assert_series_equal(s, s_orig)
else:
# original parent series is actually updated
assert s.iloc[0] == 0


@pytest.mark.parametrize(
"indexer",
[slice(0, 2), np.array([True, True, False]), np.array([0, 1])],
Expand Down
8 changes: 5 additions & 3 deletions pandas/tests/series/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,16 @@ def test_basic_getitem_dt64tz_values():
assert result == expected


def test_getitem_setitem_ellipsis():
def test_getitem_setitem_ellipsis(using_copy_on_write, warn_copy_on_write):
s = Series(np.random.default_rng(2).standard_normal(10))

result = s[...]
tm.assert_series_equal(result, s)

s[...] = 5
assert (result == 5).all()
with tm.assert_cow_warning(warn_copy_on_write):
s[...] = 5
if not using_copy_on_write:
assert (result == 5).all()


@pytest.mark.parametrize(
Expand Down
Loading