Skip to content

BUG / CoW: Series.transform not respecting CoW #53747

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

Merged
merged 1 commit into from
Jun 21, 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Enhancements
Copy-on-Write improvements
^^^^^^^^^^^^^^^^^^^^^^^^^^

- :meth:`Series.transform` not respecting Copy-on-Write when ``func`` modifies :class:`Series` inplace (:issue:`53747`)
- Calling :meth:`Index.values` will now return a read-only NumPy array (:issue:`53704`)
- Setting a :class:`Series` into a :class:`DataFrame` now creates a lazy instead of a deep copy (:issue:`53142`)
- The :class:`DataFrame` constructor, when constructing a DataFrame from a dictionary
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4499,7 +4499,8 @@ def transform(
) -> DataFrame | Series:
# Validate axis argument
self._get_axis_number(axis)
result = SeriesApply(self, func=func, args=args, kwargs=kwargs).transform()
ser = self.copy(deep=False) if using_copy_on_write() else self
result = SeriesApply(ser, func=func, args=args, kwargs=kwargs).transform()
return result

def apply(
Expand Down
26 changes: 26 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -1764,6 +1764,32 @@ def test_transpose_ea_single_column(using_copy_on_write):
assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))


def test_transform_frame(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3], "b": 1})
df_orig = df.copy()

def func(ser):
ser.iloc[0] = 100
return ser

df.transform(func)
if using_copy_on_write:
tm.assert_frame_equal(df, df_orig)


def test_transform_series(using_copy_on_write):
ser = Series([1, 2, 3])
ser_orig = ser.copy()

def func(ser):
ser.iloc[0] = 100
return ser

ser.transform(func)
if using_copy_on_write:
tm.assert_series_equal(ser, ser_orig)


def test_count_read_only_array():
df = DataFrame({"a": [1, 2], "b": 3})
result = df.count()
Expand Down