Skip to content

API / CoW: constructing DataFrame from DataFrame/BlockManager creates lazy copy #51239

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 8 commits into from
Feb 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,9 @@ Copy-on-Write improvements
a modification to the data happens) when constructing a Series from an existing
Series with the default of ``copy=False`` (:issue:`50471`)

- The :class:`DataFrame` constructor now will keep track of references when called
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC, we don't tell users about how CoW is implemented under the hood.

Maybe we can say that the constructor will obey CoW rules when called with a DataFrame.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this makes more sense, will change

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would match this sentence with the bullet point above, since it is basically the same enhancement but for DataFrame instead of Series

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

with another :class:`DataFrame` or ``BlockManager``.
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if mentioning BlockManager here is worth it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I wouldn't mention that (normal users should never pass that)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thx, removed


- Trying to set values using chained assignment (for example, ``df["a"][1:3] = 0``)
will now always raise an exception when Copy-on-Write is enabled. In this mode,
chained assignment can never work because we are always setting into a temporary
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,8 @@ def __init__(
data = data._mgr

if isinstance(data, (BlockManager, ArrayManager)):
if using_copy_on_write():
data = data.copy(deep=False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous PR only did this for DataFrame, not for BlockManager.

We have many places where we have the pattern of new_data = self._mgr.<something>; self._constructor(new_data). In those cases, I think in theory the manager method should already have taken care of the references, and so an additional shallow copy is not needed.

But, it should also be harmless (except for a bit of overheead), since those intermediate manager / blocks will go out of scope?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted to do this also for a manager, but this caused all sorts of problems because we kept the Manager alive.

Yeah this is a safety net for something like

new_data = self._mgr

if something:  # False
    ...
return self._constructor(new_data)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes if they are a true intermediate manager they go out of scope immediately. But if we forgot performing a shallow copy for some reason, this catches this

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One more thing here, do you know what is the overhead of this shallow copy? Because our "fastpath" for DataFrame creation goes through here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small test (not using this branch):

In [97]: df = pd.DataFrame({'a': [1, 2, 3], 'b': [.1, .2, .3]})

In [98]: mgr = df._mgr

In [100]: %timeit mgr.copy(deep=False)
4.1 µs ± 47.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [102]: %timeit pd.DataFrame(mgr)
1.47 µs ± 35.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

So in relative terms, it's not an insignificant change .. Not fully sure how important this is in real-world cases though.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah it's not totally cheap, it's from 1 to 3 on my machine.

We could keep it out of here if you prefer and investigate other methods of keeping the reference here?

# first check if a Manager is passed without any other arguments
# -> use fastpath (without checking Manager type)
if index is None and columns is None and dtype is None and not copy:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/reshape/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ def __init__(
# mypy needs to know sample is not an NDFrame
sample = cast("DataFrame | Series", sample)
obj = sample._constructor(obj, columns=[name], copy=False)
if using_copy_on_write():
if isinstance(original_obj, ABCSeries) and using_copy_on_write():
# TODO(CoW): Remove when ref tracking in constructors works
for i, block in enumerate(original_obj._mgr.blocks): # type: ignore[union-attr] # noqa
obj._mgr.blocks[i].refs = block.refs # type: ignore[union-attr] # noqa
Expand Down
27 changes: 26 additions & 1 deletion pandas/tests/copy_view/test_constructors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import numpy as np
import pytest

from pandas import Series
from pandas import (
DataFrame,
Series,
)
import pandas._testing as tm
from pandas.tests.copy_view.util import get_array

# -----------------------------------------------------------------------------
# Copy/view behaviour for Series / DataFrame constructors
Expand Down Expand Up @@ -73,3 +79,22 @@ def test_series_from_series_with_reindex(using_copy_on_write):
assert not np.shares_memory(ser.values, result.values)
if using_copy_on_write:
assert not result._mgr.blocks[0].refs.has_reference()


@pytest.mark.parametrize("func", [lambda x: x, lambda x: x._mgr])
@pytest.mark.parametrize("columns", [None, ["a"]])
def test_dataframe_constructor_mgr_or_df(using_copy_on_write, columns, func):
df = DataFrame({"a": [1, 2, 3]})
df_orig = df.copy()

new_df = DataFrame(func(df))

assert np.shares_memory(get_array(df, "a"), get_array(new_df, "a"))
new_df.iloc[0] = 100

if using_copy_on_write:
assert not np.shares_memory(get_array(df, "a"), get_array(new_df, "a"))
tm.assert_frame_equal(df, df_orig)
else:
assert np.shares_memory(get_array(df, "a"), get_array(new_df, "a"))
tm.assert_frame_equal(df, new_df)
4 changes: 1 addition & 3 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,8 @@ def test_constructor_dtype_nocast_view_dataframe(self, using_copy_on_write):
df = DataFrame([[1, 2]])
should_be_view = DataFrame(df, dtype=df[0].dtype)
if using_copy_on_write:
# TODO(CoW) doesn't mutate original
should_be_view.iloc[0, 0] = 99
# assert df.values[0, 0] == 1
assert df.values[0, 0] == 99
assert df.values[0, 0] == 1
else:
should_be_view[0][0] = 99
assert df.values[0, 0] == 99
Expand Down