Skip to content

ENH: Add lazy copy for truncate #50477

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
Jan 4, 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
7 changes: 4 additions & 3 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
SingleArrayManager,
)
from pandas.core.internals.construction import mgr_to_mgr
from pandas.core.internals.managers import _using_copy_on_write
from pandas.core.missing import (
clean_fill_method,
clean_reindex_fill_method,
Expand Down Expand Up @@ -9947,7 +9948,7 @@ def truncate(
before=None,
after=None,
axis: Axis | None = None,
copy: bool_t = True,
copy: bool_t | None = None,
) -> NDFrameT:
"""
Truncate a Series or DataFrame before and after some index value.
Expand Down Expand Up @@ -10098,8 +10099,8 @@ def truncate(
if isinstance(ax, MultiIndex):
setattr(result, self._get_axis_name(axis), ax.truncate(before, after))

if copy:
result = result.copy()
if copy or (copy is None and not _using_copy_on_write()):
result = result.copy(deep=copy)
Copy link
Member

Choose a reason for hiding this comment

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

This might not be needed, since the result is from an indexing operation, and already should be a lazy copy (when using a slice) with refs set up

Copy link
Member Author

Choose a reason for hiding this comment

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

We could rewrite as if copy or copy is None and _using_copy_on_write(), but we need the check for the non cow case

Copy link
Member

Choose a reason for hiding this comment

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

Should it be if copy or (copy is None and not _using_copy_on_write())? (so with brackets and when not using CoW)

Essentially we need to same behaviour as this pattern that is used elsewhere, I think:

        if copy is None:
            if _using_copy_on_write():
                copy = False
            else:
                copy = True
        if copy:
            result = result.copy()

Copy link
Member Author

Choose a reason for hiding this comment

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

Ah yes, forgot the not


return result

Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/copy_view/test_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,30 @@ def test_head_tail(method, using_copy_on_write):
tm.assert_frame_equal(df, df_orig)


@pytest.mark.parametrize(
"kwargs",
[
{"before": "a", "after": "b", "axis": 1},
{"before": 0, "after": 1, "axis": 0},
],
)
def test_truncate(using_copy_on_write, kwargs):
df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 2})
df_orig = df.copy()
df2 = df.truncate(**kwargs)
df2._mgr._verify_integrity()

if using_copy_on_write:
assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
else:
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))

df2.iloc[0, 0] = 0
if using_copy_on_write:
assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
tm.assert_frame_equal(df, df_orig)


@pytest.mark.parametrize("method", ["assign", "drop_duplicates"])
def test_assign_drop_duplicates(using_copy_on_write, method):
df = DataFrame({"a": [1, 2, 3]})
Expand Down
6 changes: 0 additions & 6 deletions pandas/tests/frame/methods/test_truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,6 @@ def test_truncate(self, datetime_frame, frame_or_series):
before=ts.index[-1] - ts.index.freq, after=ts.index[0] + ts.index.freq
)

def test_truncate_copy(self, datetime_frame):
Copy link
Member Author

Choose a reason for hiding this comment

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

This is now covered in the cow tests

index = datetime_frame.index
truncated = datetime_frame.truncate(index[5], index[10])
truncated.values[:] = 5.0
assert not (datetime_frame.values[5:11] == 5).any()

def test_truncate_nonsortedindex(self, frame_or_series):
# GH#17935

Expand Down