Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ Conversion
^^^^^^^^^^

- Bug in :meth:`DataFrame.to_dict` with ``orient='records'`` now returns python native datetime objects for datetimelike columns (:issue:`21256`)
- Bug in :meth:`Series.astype` conversion from ``string`` to ``float`` raised in presence of ``pd.NA`` values.
-

Strings
Expand Down
16 changes: 15 additions & 1 deletion pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

from pandas.core import ops
from pandas.core.array_algos import masked_reductions
from pandas.core.arrays import IntegerArray, PandasArray
from pandas.core.arrays import FloatingArray, IntegerArray, PandasArray
from pandas.core.arrays.floating import FloatingDtype
from pandas.core.arrays.integer import _IntegerDtype
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_indexer
Expand Down Expand Up @@ -298,6 +299,19 @@ def astype(self, dtype, copy=True):
arr[mask] = 0
values = arr.astype(dtype.numpy_dtype)
return IntegerArray(values, mask, copy=False)
elif isinstance(dtype, FloatingDtype):
arr = self.copy()
mask = self.isna()
arr[mask] = "0"
values = arr.astype(dtype.numpy_dtype)
return FloatingArray(values, mask, copy=False)
elif np.issubdtype(dtype, np.floating):
arr = self._ndarray.copy()
mask = self.isna()
arr[mask] = 0
values = arr.astype(dtype)
values[mask] = np.nan
return values

return super().astype(dtype, copy)

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,16 @@ def test_astype_int():
tm.assert_extension_array_equal(result, expected)


@pytest.mark.parametrize("dtype", ["float", "float32", "Float32", "Float64"])
def test_astype_float(dtype):
# Don't compare arrays (37974)
s = pd.Series(["1.1", pd.NA, "3.3"], dtype="string")

result = s.astype(dtype)
expected = pd.Series([1.1, np.nan, 3.3], dtype=dtype)
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("skipna", [True, False])
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
def test_reduce(skipna):
Expand Down