@@ -549,7 +549,7 @@ def astype(self, dtype: ExtensionDtype, copy: bool = ...) -> ExtensionArray: ...
549
549
@overload
550
550
def astype (self , dtype : AstypeArg , copy : bool = ...) -> ArrayLike : ...
551
551
552
- def astype (self , dtype : AstypeArg , copy : bool = True ) -> ArrayLike :
552
+ def astype (self , dtype : AstypeArg , copy : bool = True , errors : str = "raise" ) -> ArrayLike :
553
553
"""
554
554
Coerce this type to another dtype
555
555
@@ -560,6 +560,11 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
560
560
By default, astype always returns a newly allocated object.
561
561
If copy is set to False and dtype is categorical, the original
562
562
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
563
568
"""
564
569
dtype = pandas_dtype (dtype )
565
570
result : Categorical | np .ndarray
@@ -603,6 +608,9 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
603
608
msg = f"Cannot cast { self .categories .dtype } dtype to { dtype } "
604
609
raise ValueError (msg ) from err
605
610
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
+
606
614
result = take_nd (
607
615
new_cats , ensure_platform_int (self ._codes ), fill_value = fill_value
608
616
)
0 commit comments