Skip to content

BUG: Don't cast categorical nan to int #28438

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 18 commits into from
Sep 18, 2019
3 changes: 3 additions & 0 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,9 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
if dtype == self.dtype:
return self
return self._set_dtype(dtype)
if is_integer_dtype(dtype) and self.isin([np.nan, -np.inf, np.inf]).any():
msg = "Cannot cast to int."
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ValueError: cannot convert float NaN to integer is what we do now on
pd.Series([1,2,np.nan],dtype='Int64').astype('int') so would replicate this message

raise ValueError(msg)
return np.array(self, dtype=dtype, copy=copy)

@cache_readonly
Expand Down
9 changes: 8 additions & 1 deletion pandas/tests/extension/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,14 @@ def test_searchsorted(self, data_for_sorting):


class TestCasting(base.BaseCastingTests):
pass
def test_cast_nan_to_int(self):
s1 = pd.Series([0, 1, np.nan], dtype="category")
s2 = pd.Series([0, 1, np.inf], dtype="category")

with pytest.raises(ValueError):
s1.astype(int)
with pytest.raises(ValueError):
s2.astype(int)


class TestArithmeticOps(base.BaseArithmeticOpsTests):
Expand Down