Skip to content

Commit 845c50c

Browse files
BUG: implement astype from string dtype to nullable int dtype (#33062)
1 parent c69f7d8 commit 845c50c

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v1.1.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ Conversion
314314
Strings
315315
^^^^^^^
316316

317-
-
317+
- Bug in the :meth:`~Series.astype` method when converting "string" dtype data to nullable integer dtype (:issue:`32450`).
318318
-
319319

320320

pandas/core/arrays/string_.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313

1414
from pandas import compat
1515
from pandas.core import ops
16-
from pandas.core.arrays import PandasArray
16+
from pandas.core.arrays import IntegerArray, PandasArray
17+
from pandas.core.arrays.integer import _IntegerDtype
1718
from pandas.core.construction import extract_array
1819
from pandas.core.indexers import check_array_indexer
1920
from pandas.core.missing import isna
@@ -271,6 +272,13 @@ def astype(self, dtype, copy=True):
271272
if copy:
272273
return self.copy()
273274
return self
275+
elif isinstance(dtype, _IntegerDtype):
276+
arr = self._ndarray.copy()
277+
mask = self.isna()
278+
arr[mask] = 0
279+
values = arr.astype(dtype.numpy_dtype)
280+
return IntegerArray(values, mask, copy=False)
281+
274282
return super().astype(dtype, copy)
275283

276284
def _reduce(self, name, skipna=True, **kwargs):

pandas/tests/arrays/string_/test_string.py

+8
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,14 @@ def test_from_sequence_no_mutate(copy):
214214
tm.assert_numpy_array_equal(a, original)
215215

216216

217+
def test_astype_int():
218+
arr = pd.array(["1", pd.NA, "3"], dtype="string")
219+
220+
result = arr.astype("Int64")
221+
expected = pd.array([1, pd.NA, 3], dtype="Int64")
222+
tm.assert_extension_array_equal(result, expected)
223+
224+
217225
@pytest.mark.parametrize("skipna", [True, False])
218226
@pytest.mark.xfail(reason="Not implemented StringArray.sum")
219227
def test_reduce(skipna):

0 commit comments

Comments
 (0)