diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 95804de2a7089..f6dfc7d3b076a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -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, @@ -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. @@ -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) return result diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 2b3d13b982d4d..e24babd46fea9 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -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]}) diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py index bfee3edc085d8..21f0664707ebe 100644 --- a/pandas/tests/frame/methods/test_truncate.py +++ b/pandas/tests/frame/methods/test_truncate.py @@ -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): - 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