Skip to content

Commit 934147b

Browse files
committed
BUG: Fixed failure to copy in astype
1 parent bfcda0d commit 934147b

File tree

4 files changed

+19
-0
lines changed

4 files changed

+19
-0
lines changed

doc/source/whatsnew/v1.0.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ Bug fixes
6464
**Datetimelike**
6565

6666
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with a tz-aware index (:issue:`26683`)
67+
- Bug in :meth:`Series.astype` not copying for tz-naive and tz-aware datetime64 dtyep (:issue:`32490`)
6768
- Bug where :func:`to_datetime` would raise when passed ``pd.NA`` (:issue:`32213`)
6869

6970
**Categorical**

pandas/core/arrays/datetimes.py

+3
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,7 @@ def astype(self, dtype, copy=True):
579579
# --> datetime
580580
# --> period
581581
# DatetimeLikeArrayMixin Super handles the rest.
582+
# breakpoint()
582583
dtype = pandas_dtype(dtype)
583584

584585
if is_datetime64_ns_dtype(dtype) and not is_dtype_equal(dtype, self.dtype):
@@ -587,6 +588,8 @@ def astype(self, dtype, copy=True):
587588
if getattr(self.dtype, "tz", None) is None:
588589
return self.tz_localize(new_tz)
589590
result = self.tz_convert(new_tz)
591+
if copy:
592+
result = result.copy()
590593
if new_tz is None:
591594
# Do we want .astype('datetime64[ns]') to be an ndarray.
592595
# The astype in Block._astype expects this to return an

pandas/core/internals/blocks.py

+3
Original file line numberDiff line numberDiff line change
@@ -2228,6 +2228,9 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
22282228
# if we are passed a datetime64[ns, tz]
22292229
if is_datetime64tz_dtype(dtype):
22302230
values = self.values
2231+
if copy:
2232+
# this should be the only copy
2233+
values = values.copy()
22312234
if getattr(values, "tz", None) is None:
22322235
values = DatetimeArray(values).tz_localize("UTC")
22332236
values = values.tz_convert(dtype.tz)

pandas/tests/arrays/test_datetimes.py

+12
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,18 @@ def test_astype_to_same(self):
151151
result = arr.astype(DatetimeTZDtype(tz="US/Central"), copy=False)
152152
assert result is arr
153153

154+
@pytest.mark.parametrize("dtype", ["datetime64[ns]", "datetime64[ns, UTC]"])
155+
@pytest.mark.parametrize(
156+
"other", ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, CET]"]
157+
)
158+
def test_astype_copies(self, dtype, other):
159+
# https://github.com/pandas-dev/pandas/pull/32490
160+
s = pd.Series([1, 2], dtype=dtype)
161+
orig = s.copy()
162+
t = s.astype(other)
163+
t[:] = pd.NaT
164+
tm.assert_series_equal(s, orig)
165+
154166
@pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
155167
def test_astype_int(self, dtype):
156168
arr = DatetimeArray._from_sequence([pd.Timestamp("2000"), pd.Timestamp("2001")])

0 commit comments

Comments
 (0)