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 not np.isfinite(self.__array__()).all():
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
10 changes: 8 additions & 2 deletions pandas/tests/extension/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import pytest

import pandas as pd
from pandas import Categorical
from pandas import Categorical, CategoricalIndex
from pandas.api.types import CategoricalDtype
from pandas.tests.extension import base
import pandas.util.testing as tm
Expand Down Expand Up @@ -197,7 +197,13 @@ def test_searchsorted(self, data_for_sorting):


class TestCasting(base.BaseCastingTests):
pass
@pytest.mark.parametrize("cls", [Categorical, CategoricalIndex])
@pytest.mark.parametrize("value", [np.nan, -np.inf, np.inf])
def test_cast_nan_to_int(self, cls, value):
s = cls([0, 1, value])

with pytest.raises((ValueError, TypeError)):
s.astype(int)


class TestArithmeticOps(base.BaseArithmeticOpsTests):
Expand Down