Skip to content

Commit c4a84ab

Browse files
authored
ENH: Add lazy copy for tz_convert and tz_localize (#50490)
1 parent b29db1b commit c4a84ab

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

pandas/core/generic.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10106,7 +10106,7 @@ def truncate(
1010610106
@final
1010710107
@doc(klass=_shared_doc_kwargs["klass"])
1010810108
def tz_convert(
10109-
self: NDFrameT, tz, axis: Axis = 0, level=None, copy: bool_t = True
10109+
self: NDFrameT, tz, axis: Axis = 0, level=None, copy: bool_t | None = None
1011010110
) -> NDFrameT:
1011110111
"""
1011210112
Convert tz-aware axis to target time zone.
@@ -10188,7 +10188,7 @@ def tz_localize(
1018810188
tz,
1018910189
axis: Axis = 0,
1019010190
level=None,
10191-
copy: bool_t = True,
10191+
copy: bool_t | None = None,
1019210192
ambiguous: TimeAmbiguous = "raise",
1019310193
nonexistent: TimeNonexistent = "raise",
1019410194
) -> NDFrameT:

pandas/tests/copy_view/test_methods.py

+23
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
Index,
77
MultiIndex,
88
Series,
9+
date_range,
910
)
1011
import pandas._testing as tm
1112
from pandas.tests.copy_view.util import get_array
@@ -460,6 +461,28 @@ def test_frame_set_axis(using_copy_on_write):
460461
tm.assert_frame_equal(df, df_orig)
461462

462463

464+
@pytest.mark.parametrize(
465+
"func, tz", [("tz_convert", "Europe/Berlin"), ("tz_localize", None)]
466+
)
467+
def test_tz_convert_localize(using_copy_on_write, func, tz):
468+
# GH 49473
469+
ser = Series(
470+
[1, 2], index=date_range(start="2014-08-01 09:00", freq="H", periods=2, tz=tz)
471+
)
472+
ser_orig = ser.copy()
473+
ser2 = getattr(ser, func)("US/Central")
474+
475+
if using_copy_on_write:
476+
assert np.shares_memory(ser.values, ser2.values)
477+
else:
478+
assert not np.shares_memory(ser.values, ser2.values)
479+
480+
# mutating ser triggers a copy-on-write for the column / block
481+
ser2.iloc[0] = 0
482+
assert not np.shares_memory(ser2.values, ser.values)
483+
tm.assert_series_equal(ser, ser_orig)
484+
485+
463486
def test_series_set_axis(using_copy_on_write):
464487
# GH 49473
465488
ser = Series([1, 2, 3])

0 commit comments

Comments
 (0)