Skip to content

CoW: Ensure that iterrows does not allow mutating parent #51271

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 4 commits into from
Feb 16, 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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ Copy-on-Write improvements
- :meth:`DataFrame.to_timestamp` / :meth:`Series.to_timestamp`
- :meth:`DataFrame.to_period` / :meth:`Series.to_period`
- :meth:`DataFrame.truncate`
- :meth:`DataFrame.iterrows`
- :meth:`DataFrame.tz_convert` / :meth:`Series.tz_localize`
- :meth:`DataFrame.fillna` / :meth:`Series.fillna`
- :meth:`DataFrame.interpolate` / :meth:`Series.interpolate`
Expand Down
6 changes: 6 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1392,8 +1392,14 @@ def iterrows(self) -> Iterable[tuple[Hashable, Series]]:
"""
columns = self.columns
klass = self._constructor_sliced
using_cow = using_copy_on_write()
for k, v in zip(self.index, self.values):
s = klass(v, index=columns, name=k).__finalize__(self)
if using_cow and self._mgr.is_single_block:
s._mgr.blocks[0].refs = self._mgr.blocks[0].refs # type: ignore[union-attr] # noqa
s._mgr.blocks[0].refs.add_reference( # type: ignore[union-attr]
s._mgr.blocks[0] # type: ignore[arg-type, union-attr]
)
yield k, s

def itertuples(
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -1329,6 +1329,16 @@ def test_asfreq_noop(using_copy_on_write):
tm.assert_frame_equal(df, df_orig)


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

for _, sub in df.iterrows():
sub.iloc[0] = 100
if using_copy_on_write:
tm.assert_frame_equal(df, df_orig)


def test_interpolate_creates_copy(using_copy_on_write):
# GH#51126
df = DataFrame({"a": [1.5, np.nan, 3]})
Expand Down