diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index ff3e018779b02..fa856f7a2a1d3 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -158,6 +158,7 @@ Bug fixes Categorical ^^^^^^^^^^^ +- Bug in :meth:`Categorical.view` not accepting integer dtypes (:issue:`25464`) - Bug in :meth:`CategoricalIndex.union` when the index's categories are integer-dtype and the index contains ``NaN`` values incorrectly raising instead of casting to ``float64`` (:issue:`45362`) - diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c46e2ae46c15b..3d9d3ef8a2557 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1911,11 +1911,6 @@ def _values_for_rank(self): ) return values - def view(self, dtype=None): - if dtype is not None: - raise NotImplementedError(dtype) - return self._from_backing_data(self._ndarray) - def to_dense(self) -> np.ndarray: """ Return my 'dense' representation diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 2ae6ce99b4ee8..ccdf2edc3ea68 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -290,6 +290,24 @@ def test_map_str(self): class TestCategoricalIndex2: # Tests that are not overriding a test in Base + def test_view_i8(self): + # GH#25464 + ci = tm.makeCategoricalIndex(100) + msg = "When changing to a larger dtype, its size must be a divisor" + with pytest.raises(ValueError, match=msg): + ci.view("i8") + with pytest.raises(ValueError, match=msg): + ci._data.view("i8") + + ci = ci[:-4] # length divisible by 8 + + res = ci.view("i8") + expected = ci._data.codes.view("i8") + tm.assert_numpy_array_equal(res, expected) + + cat = ci._data + tm.assert_numpy_array_equal(cat.view("i8"), expected) + @pytest.mark.parametrize( "dtype, engine_type", [