Skip to content

Commit df401f2

Browse files
phoflpunndcoder28
authored andcommitted
BUG / CoW: Series.transform not respecting CoW (pandas-dev#53747)
1 parent 1def29f commit df401f2

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

doc/source/whatsnew/v2.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Enhancements
1919
Copy-on-Write improvements
2020
^^^^^^^^^^^^^^^^^^^^^^^^^^
2121

22+
- :meth:`Series.transform` not respecting Copy-on-Write when ``func`` modifies :class:`Series` inplace (:issue:`53747`)
2223
- Calling :meth:`Index.values` will now return a read-only NumPy array (:issue:`53704`)
2324
- Setting a :class:`Series` into a :class:`DataFrame` now creates a lazy instead of a deep copy (:issue:`53142`)
2425
- The :class:`DataFrame` constructor, when constructing a DataFrame from a dictionary

pandas/core/series.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4499,7 +4499,8 @@ def transform(
44994499
) -> DataFrame | Series:
45004500
# Validate axis argument
45014501
self._get_axis_number(axis)
4502-
result = SeriesApply(self, func=func, args=args, kwargs=kwargs).transform()
4502+
ser = self.copy(deep=False) if using_copy_on_write() else self
4503+
result = SeriesApply(ser, func=func, args=args, kwargs=kwargs).transform()
45034504
return result
45044505

45054506
def apply(

pandas/tests/copy_view/test_methods.py

+26
Original file line numberDiff line numberDiff line change
@@ -1764,6 +1764,32 @@ def test_transpose_ea_single_column(using_copy_on_write):
17641764
assert not np.shares_memory(get_array(df, "a"), get_array(result, 0))
17651765

17661766

1767+
def test_transform_frame(using_copy_on_write):
1768+
df = DataFrame({"a": [1, 2, 3], "b": 1})
1769+
df_orig = df.copy()
1770+
1771+
def func(ser):
1772+
ser.iloc[0] = 100
1773+
return ser
1774+
1775+
df.transform(func)
1776+
if using_copy_on_write:
1777+
tm.assert_frame_equal(df, df_orig)
1778+
1779+
1780+
def test_transform_series(using_copy_on_write):
1781+
ser = Series([1, 2, 3])
1782+
ser_orig = ser.copy()
1783+
1784+
def func(ser):
1785+
ser.iloc[0] = 100
1786+
return ser
1787+
1788+
ser.transform(func)
1789+
if using_copy_on_write:
1790+
tm.assert_series_equal(ser, ser_orig)
1791+
1792+
17671793
def test_count_read_only_array():
17681794
df = DataFrame({"a": [1, 2], "b": 3})
17691795
result = df.count()

0 commit comments

Comments
 (0)