Skip to content

Commit c513854

Browse files
Backport PR pandas-dev#41958: REGR: Series[dt64/td64].astype(string) (pandas-dev#42028)
Co-authored-by: jbrockmendel <[email protected]>
1 parent 45c3b3b commit c513854

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

pandas/_libs/lib.pyx

+8
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,14 @@ cpdef ndarray[object] ensure_string_array(
716716
Py_ssize_t i = 0, n = len(arr)
717717

718718
if hasattr(arr, "to_numpy"):
719+
720+
if hasattr(arr, "dtype") and arr.dtype.kind in ["m", "M"]:
721+
# dtype check to exclude DataFrame
722+
# GH#41409 TODO: not a great place for this
723+
out = arr.astype(str).astype(object)
724+
out[arr.isna()] = na_value
725+
return out
726+
719727
arr = arr.to_numpy()
720728
elif not isinstance(arr, np.ndarray):
721729
arr = np.array(arr, dtype="object")

pandas/tests/frame/methods/test_astype.py

+11-6
Original file line numberDiff line numberDiff line change
@@ -632,13 +632,9 @@ def test_astype_tz_object_conversion(self, tz):
632632
result = result.astype({"tz": "datetime64[ns, Europe/London]"})
633633
tm.assert_frame_equal(result, expected)
634634

635-
def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request):
635+
def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture):
636+
# GH#41409
636637
tz = tz_naive_fixture
637-
if tz is None:
638-
mark = pytest.mark.xfail(
639-
reason="GH#36153 uses ndarray formatting instead of DTA formatting"
640-
)
641-
request.node.add_marker(mark)
642638

643639
dti = date_range("2016-01-01", periods=3, tz=tz)
644640
dta = dti._data
@@ -660,6 +656,15 @@ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request)
660656
alt = obj.astype(str)
661657
assert np.all(alt.iloc[1:] == result.iloc[1:])
662658

659+
def test_astype_td64_to_string(self, frame_or_series):
660+
# GH#41409
661+
tdi = pd.timedelta_range("1 Day", periods=3)
662+
obj = frame_or_series(tdi)
663+
664+
expected = frame_or_series(["1 days", "2 days", "3 days"], dtype="string")
665+
result = obj.astype("string")
666+
tm.assert_equal(result, expected)
667+
663668
def test_astype_bytes(self):
664669
# GH#39474
665670
result = DataFrame(["foo", "bar", "baz"]).astype(bytes)

0 commit comments

Comments
 (0)