Skip to content

Commit b9e5d5d

Browse files
zmoontwoertwein
authored andcommitted
Support DataFrame.astype('category') (pandas-dev#559)
* Add test for Series as CategoricalDtype * Add `CategoryDtypeArg` to `AstypeArg` * Apply review suggestions * Add test for `DataFrame.astype('category')`
1 parent 7c42ae2 commit b9e5d5d

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

pandas-stubs/_typing.pyi

+2-2
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ ComplexDtypeArg: TypeAlias = (
148148
)
149149
TimedeltaDtypeArg: TypeAlias = Literal["timedelta64[ns]"]
150150
TimestampDtypeArg: TypeAlias = Literal["datetime64[ns]"]
151-
CategoryDtypeArg: TypeAlias = Literal["category"]
151+
CategoryDtypeArg: TypeAlias = CategoricalDtype | Literal["category"]
152152

153153
AstypeArg: TypeAlias = (
154154
BooleanDtypeArg
@@ -159,7 +159,7 @@ AstypeArg: TypeAlias = (
159159
| ComplexDtypeArg
160160
| TimedeltaDtypeArg
161161
| TimestampDtypeArg
162-
| CategoricalDtype
162+
| CategoryDtypeArg
163163
| ExtensionDtype
164164
)
165165
# DtypeArg specifies all allowable dtypes in a functions its dtype argument

tests/test_frame.py

+2
Original file line numberDiff line numberDiff line change
@@ -2442,3 +2442,5 @@ def test_astype() -> None:
24422442
assert_type(ab.astype({"col1": "int32", "col2": str}), "pd.DataFrame"),
24432443
pd.DataFrame,
24442444
)
2445+
check(assert_type(s.astype(pd.CategoricalDtype()), "pd.DataFrame"), pd.DataFrame)
2446+
check(assert_type(s.astype("category"), "pd.DataFrame"), pd.DataFrame) # GH 559

tests/test_series.py

+12
Original file line numberDiff line numberDiff line change
@@ -1591,3 +1591,15 @@ def test_updated_astype() -> None:
15911591
pd.Series,
15921592
Decimal,
15931593
)
1594+
1595+
# Categorical
1596+
check(
1597+
assert_type(s.astype(pd.CategoricalDtype()), "pd.Series[Any]"),
1598+
pd.Series,
1599+
np.integer,
1600+
)
1601+
check(
1602+
assert_type(s.astype("category"), "pd.Series[Any]"),
1603+
pd.Series,
1604+
np.integer,
1605+
)

0 commit comments

Comments
 (0)