Skip to content

Commit dfb693e

Browse files
jbrockmendelmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#35633: BUG: DataFrame.apply with func altering row in-place
1 parent 7957254 commit dfb693e

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

doc/source/whatsnew/v1.1.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Fixed regressions
2121
- Fixed regression in :class:`pandas.core.groupby.RollingGroupby` where column selection was ignored (:issue:`35486`)
2222
- Fixed regression in :meth:`DataFrame.shift` with ``axis=1`` and heterogeneous dtypes (:issue:`35488`)
2323
- Fixed regression in ``.groupby(..).rolling(..)`` where a segfault would occur with ``center=True`` and an odd number of values (:issue:`35552`)
24+
- Fixed regression in :meth:`DataFrame.apply` where functions that altered the input in-place only operated on a single row (:issue:`35462`)
2425

2526
.. ---------------------------------------------------------------------------
2627

pandas/core/apply.py

+2
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,8 @@ def series_generator(self):
389389
blk = mgr.blocks[0]
390390

391391
for (arr, name) in zip(values, self.index):
392+
# GH#35462 re-pin mgr in case setitem changed it
393+
ser._mgr = mgr
392394
blk.values = arr
393395
ser.name = name
394396
yield ser

pandas/tests/frame/apply/test_frame_apply.py

+19
Original file line numberDiff line numberDiff line change
@@ -1522,3 +1522,22 @@ def test_apply_dtype(self, col):
15221522
expected = df.dtypes
15231523

15241524
tm.assert_series_equal(result, expected)
1525+
1526+
1527+
def test_apply_mutating():
1528+
# GH#35462 case where applied func pins a new BlockManager to a row
1529+
df = pd.DataFrame({"a": range(100), "b": range(100, 200)})
1530+
1531+
def func(row):
1532+
mgr = row._mgr
1533+
row.loc["a"] += 1
1534+
assert row._mgr is not mgr
1535+
return row
1536+
1537+
expected = df.copy()
1538+
expected["a"] += 1
1539+
1540+
result = df.apply(func, axis=1)
1541+
1542+
tm.assert_frame_equal(result, expected)
1543+
tm.assert_frame_equal(df, result)

0 commit comments

Comments
 (0)