Skip to content

Commit f773083

Browse files
authored
BUG: fix Categorical.astype for dtype=np.int32 argument (#39615)
1 parent e58a193 commit f773083

File tree

5 files changed

+43
-5
lines changed

5 files changed

+43
-5
lines changed

doc/source/whatsnew/v1.2.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Fixed regressions
2121
- Fixed regression in :meth:`~DataFrame.to_pickle` failing to create bz2/xz compressed pickle files with ``protocol=5`` (:issue:`39002`)
2222
- Fixed regression in :func:`pandas.testing.assert_series_equal` and :func:`pandas.testing.assert_frame_equal` always raising ``AssertionError`` when comparing extension dtypes (:issue:`39410`)
2323
- Fixed regression in :meth:`~DataFrame.to_csv` opening ``codecs.StreamWriter`` in binary mode instead of in text mode and ignoring user-provided ``mode`` (:issue:`39247`)
24+
- Fixed regression in :meth:`Categorical.astype` casting to incorrect dtype when ``np.int32`` is passed to dtype argument (:issue:`39402`)
2425
- Fixed regression in :meth:`~DataFrame.to_excel` creating corrupt files when appending (``mode="a"``) to an existing file (:issue:`39576`)
2526
- Fixed regression in :meth:`DataFrame.transform` failing in case of an empty DataFrame or Series (:issue:`39636`)
2627
- Fixed regression in :meth:`~DataFrame.groupby` or :meth:`~DataFrame.resample` when aggregating an all-NaN or numeric object dtype column (:issue:`39329`)

pandas/conftest.py

+26
Original file line numberDiff line numberDiff line change
@@ -1242,6 +1242,32 @@ def any_nullable_int_dtype(request):
12421242
return request.param
12431243

12441244

1245+
@pytest.fixture(params=tm.ALL_INT_DTYPES + tm.ALL_EA_INT_DTYPES)
1246+
def any_int_or_nullable_int_dtype(request):
1247+
"""
1248+
Parameterized fixture for any nullable integer dtype.
1249+
1250+
* int
1251+
* 'int8'
1252+
* 'uint8'
1253+
* 'int16'
1254+
* 'uint16'
1255+
* 'int32'
1256+
* 'uint32'
1257+
* 'int64'
1258+
* 'uint64'
1259+
* 'UInt8'
1260+
* 'Int8'
1261+
* 'UInt16'
1262+
* 'Int16'
1263+
* 'UInt32'
1264+
* 'Int32'
1265+
* 'UInt64'
1266+
* 'Int64'
1267+
"""
1268+
return request.param
1269+
1270+
12451271
@pytest.fixture(params=tm.ALL_EA_INT_DTYPES + tm.FLOAT_EA_DTYPES)
12461272
def any_nullable_numeric_dtype(request):
12471273
"""

pandas/core/arrays/categorical.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -466,16 +466,16 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
466466
else:
467467
# GH8628 (PERF): astype category codes instead of astyping array
468468
try:
469-
astyped_cats = self.categories.astype(dtype=dtype, copy=copy)
469+
new_cats = np.asarray(self.categories)
470+
new_cats = new_cats.astype(dtype=dtype, copy=copy)
470471
except (
471472
TypeError, # downstream error msg for CategoricalIndex is misleading
472473
ValueError,
473474
):
474475
msg = f"Cannot cast {self.categories.dtype} dtype to {dtype}"
475476
raise ValueError(msg)
476477

477-
astyped_cats = extract_array(astyped_cats, extract_numpy=True)
478-
result = take_1d(astyped_cats, libalgos.ensure_platform_int(self._codes))
478+
result = take_1d(new_cats, libalgos.ensure_platform_int(self._codes))
479479

480480
return result
481481

pandas/tests/arrays/categorical/test_dtypes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def test_astype(self, ordered):
138138
tm.assert_numpy_array_equal(result, expected)
139139

140140
result = cat.astype(int)
141-
expected = np.array(cat, dtype="int64")
141+
expected = np.array(cat, dtype="int")
142142
tm.assert_numpy_array_equal(result, expected)
143143

144144
result = cat.astype(float)

pandas/tests/series/test_dtypes.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def test_astype_categorical_to_other(self):
6868
exp = Series(["a", "b", "b", "a", "a", "c", "c", "c"])
6969
tm.assert_series_equal(cat.astype("str"), exp)
7070
s2 = Series(Categorical(["1", "2", "3", "4"]))
71-
exp2 = Series([1, 2, 3, 4]).astype("int64")
71+
exp2 = Series([1, 2, 3, 4]).astype("int")
7272
tm.assert_series_equal(s2.astype("int"), exp2)
7373

7474
# object don't sort correctly, so just compare that we have the same
@@ -94,6 +94,17 @@ def cmp(a, b):
9494
result = ser.astype("object").astype(CategoricalDtype())
9595
tm.assert_series_equal(result, roundtrip_expected)
9696

97+
def test_categorical_astype_to_int(self, any_int_or_nullable_int_dtype):
98+
# GH 39402
99+
100+
df = DataFrame(data={"col1": pd.array([2.0, 1.0, 3.0])})
101+
df.col1 = df.col1.astype("category")
102+
df.col1 = df.col1.astype(any_int_or_nullable_int_dtype)
103+
expected = DataFrame(
104+
{"col1": pd.array([2, 1, 3], dtype=any_int_or_nullable_int_dtype)}
105+
)
106+
tm.assert_frame_equal(df, expected)
107+
97108
def test_series_to_categorical(self):
98109
# see gh-16524: test conversion of Series to Categorical
99110
series = Series(["a", "b", "c"])

0 commit comments

Comments
 (0)