Skip to content

Commit e67d66b

Browse files
author
acr-bot
committed
Fix #1
1 parent fa56867 commit e67d66b

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

pandas/core/arrays/categorical.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,7 +549,7 @@ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray: ...
549549
@overload
550550
def astype(self, dtype: AstypeArg, copy: bool = ...) -> ArrayLike: ...
551551

552-
def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
552+
def astype(self, dtype: AstypeArg, copy: bool = True, errors: str = "raise") -> ArrayLike:
553553
"""
554554
Coerce this type to another dtype
555555
@@ -560,6 +560,11 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
560560
By default, astype always returns a newly allocated object.
561561
If copy is set to False and dtype is categorical, the original
562562
object is returned.
563+
errors : {'raise', 'ignore'}, default 'raise'
564+
Control raising of exceptions on invalid data for provided dtype.
565+
566+
- 'raise' : allow exceptions to be raised
567+
- 'ignore' : suppress exceptions. On error return original object
563568
"""
564569
dtype = pandas_dtype(dtype)
565570
result: Categorical | np.ndarray
@@ -603,6 +608,9 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
603608
msg = f"Cannot cast {self.categories.dtype} dtype to {dtype}"
604609
raise ValueError(msg) from err
605610

611+
if errors == "raise" and not np.all(np.isin(self.codes, new_cats)):
612+
raise ValueError("Cannot convert to CategoricalDtype with undefined values")
613+
606614
result = take_nd(
607615
new_cats, ensure_platform_int(self._codes), fill_value=fill_value
608616
)

0 commit comments

Comments
 (0)