Skip to content

Commit 8f99187

Browse files
Backport PR #37034 on branch 1.1.x (REGR: Fix casting of None to str during astype) (#37076)
Co-authored-by: Daniel Saxton <[email protected]>
1 parent 42c2c74 commit 8f99187

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

doc/source/whatsnew/v1.1.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Fixed regressions
1818
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
1919
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
2020
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
21+
- Fixed regression in :meth:`Series.astype` converting ``None`` to ``"nan"`` when casting to string (:issue:`36904`)
2122
- Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`)
2223

2324
.. ---------------------------------------------------------------------------

pandas/core/dtypes/cast.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -922,7 +922,9 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
922922
dtype = pandas_dtype(dtype)
923923

924924
if issubclass(dtype.type, str):
925-
return lib.ensure_string_array(arr.ravel(), skipna=skipna).reshape(arr.shape)
925+
return lib.ensure_string_array(
926+
arr.ravel(), skipna=skipna, convert_na_value=False
927+
).reshape(arr.shape)
926928

927929
elif is_datetime64_dtype(arr):
928930
if is_object_dtype(dtype):

pandas/tests/series/methods/test_astype.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import numpy as np
22
import pytest
33

4-
from pandas import Interval, Series, Timestamp, date_range
4+
from pandas import NA, Interval, Series, Timestamp, date_range
55
import pandas._testing as tm
66

77

@@ -55,3 +55,13 @@ def test_astype_from_float_to_str(self, dtype):
5555
result = s.astype(str)
5656
expected = Series(["0.1"])
5757
tm.assert_series_equal(result, expected)
58+
59+
@pytest.mark.parametrize(
60+
"value, string_value", [(None, "None"), (np.nan, "nan"), (NA, "<NA>")],
61+
)
62+
def test_astype_to_str_preserves_na(self, value, string_value):
63+
# https://github.com/pandas-dev/pandas/issues/36904
64+
s = Series(["a", "b", value], dtype=object)
65+
result = s.astype(str)
66+
expected = Series(["a", "b", string_value], dtype=object)
67+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)