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 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
4 changes: 4 additions & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,10 @@ 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 will now create a lazy copy (deferring the copy until
a modification to the data happens) when constructing from an existing
:class:`DataFrame` with the default of ``copy=False`` (:issue:`51239`)

- The :class:`DataFrame` constructor, when constructing a DataFrame from a dictionary
of Series objects and specifying ``copy=False``, will now use a lazy copy
of those Series objects for the columns of the DataFrame (:issue:`50777`)
Expand Down
2 changes: 2 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,8 @@ def __init__(
data = data.copy(deep=False)

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
19 changes: 19 additions & 0 deletions pandas/tests/copy_view/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,25 @@ def test_series_from_series_with_reindex(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)


@pytest.mark.parametrize("dtype", [None, "int64", "Int64"])
@pytest.mark.parametrize("index", [None, [0, 1, 2]])
@pytest.mark.parametrize("columns", [None, ["a", "b"], ["a", "b", "c"]])
Expand Down