Skip to content

Fix StringArray.astype for category dtype #40450

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Apr 2, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 4 additions & 1 deletion pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@
from pandas.core import ops
from pandas.core.array_algos import masked_reductions
from pandas.core.arrays import (
Categorical,
FloatingArray,
IntegerArray,
PandasArray,
)
from pandas.core.arrays.categorical import CategoricalDtype
from pandas.core.arrays.floating import FloatingDtype
from pandas.core.arrays.integer import _IntegerDtype
from pandas.core.construction import extract_array
Expand Down Expand Up @@ -307,7 +309,6 @@ def __setitem__(self, key, value):

def astype(self, dtype, copy=True):
dtype = pandas_dtype(dtype)

if is_dtype_equal(dtype, self.dtype):
if copy:
return self.copy()
Expand All @@ -327,6 +328,8 @@ def astype(self, dtype, copy=True):
arr[mask] = "0"
values = arr.astype(dtype.numpy_dtype)
return FloatingArray(values, mask, copy=False)
elif isinstance(dtype, CategoricalDtype):
return Categorical(self, dtype=dtype, copy=copy)
elif np.issubdtype(dtype, np.floating):
arr = self._ndarray.copy()
mask = self.isna()
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/series/methods/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,13 @@ def test_astype_categories_raises(self):
with pytest.raises(TypeError, match="got an unexpected"):
s.astype("category", categories=["a", "b"], ordered=True)

def test_astype_str_to_categorical(self):
# GH-40351
s = Series(["A", np.NaN], dtype="string")
result = s.astype("category")
expected = Series(["A", np.NaN], dtype="category")
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize("items", [["a", "b", "c", "a"], [1, 2, 3, 1]])
def test_astype_from_categorical(self, items):
ser = Series(items)
Expand Down