Skip to content

Commit a6fa8b4

Browse files
dsaxtonKevin D Smith
authored and
Kevin D Smith
committed
REGR: Fix casting of None to str during astype (pandas-dev#37034)
1 parent 31bb3c4 commit a6fa8b4

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-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

2223
.. ---------------------------------------------------------------------------
2324

pandas/core/dtypes/cast.py

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

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

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

pandas/tests/series/methods/test_astype.py

+16-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,18 @@ 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",
61+
[
62+
(None, "None"),
63+
(np.nan, "nan"),
64+
(NA, "<NA>"),
65+
],
66+
)
67+
def test_astype_to_str_preserves_na(self, value, string_value):
68+
# https://github.com/pandas-dev/pandas/issues/36904
69+
s = Series(["a", "b", value], dtype=object)
70+
result = s.astype(str)
71+
expected = Series(["a", "b", string_value], dtype=object)
72+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)