Skip to content

BUG-CoW: from_records not tracking references when called with df #52029

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 3 commits into from
Mar 17, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
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 @@ -190,6 +190,9 @@ Copy-on-Write improvements
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`)

- The :meth:`DataFrame.from_records` will now respect Copy-on-Write when called
with a :class:`DataFrame`.

- Trying to set values using chained assignment (for example, ``df["a"][1:3] = 0``)
will now always raise an warning 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: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2205,7 +2205,7 @@ def from_records(
data = data.set_index(index)
if exclude is not None:
data = data.drop(columns=exclude)
return data
return data.copy(deep=False)

result_index = None

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/copy_view/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,18 @@ def test_dataframe_from_dict_of_series_with_dtype(index):
df.iloc[0, 0] = 100
arr_after = get_array(df, "a")
assert np.shares_memory(arr_before, arr_after)


def test_dataframe_from_records_with_dataframe(using_copy_on_write):
df = DataFrame({"a": [1, 2, 3]})
df_orig = df.copy()
with tm.assert_produces_warning(FutureWarning):
df2 = DataFrame.from_records(df)
if using_copy_on_write:
assert not df._mgr._has_no_reference(0)
assert np.shares_memory(get_array(df, "a"), get_array(df2, "a"))
df2.iloc[0, 0] = 100
if using_copy_on_write:
tm.assert_frame_equal(df, df_orig)
else:
tm.assert_frame_equal(df, df2)