@@ -577,11 +577,12 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
577577 raise ValueError ("Cannot convert float NaN to integer" )
578578
579579 elif len (self .codes ) == 0 or len (self .categories ) == 0 :
580- result = np .array (
581- self ,
582- dtype = dtype ,
583- copy = copy ,
584- )
580+ # For NumPy 1.x compatibility we cannot use copy=None. And
581+ # `copy=False` has the meaning of `copy=None` here:
582+ if not copy :
583+ result = np .asarray (self , dtype = dtype )
584+ else :
585+ result = np .array (self , dtype = dtype )
585586
586587 else :
587588 # GH8628 (PERF): astype category codes instead of astyping array
@@ -1642,6 +1643,17 @@ def __array__(
16421643 """
16431644 The numpy array interface.
16441645
1646+ Users should not call this directly. Rather, it is invoked by
1647+ :func:`numpy.array` and :func:`numpy.asarray`.
1648+
1649+ Parameters
1650+ ----------
1651+ dtype : np.dtype or None
1652+ Specifies the the dtype for the array.
1653+
1654+ copy : bool or None, optional
1655+ See :func:`numpy.asarray`.
1656+
16451657 Returns
16461658 -------
16471659 numpy.array
@@ -1659,13 +1671,18 @@ def __array__(
16591671 >>> np.asarray(cat)
16601672 array(['a', 'b'], dtype=object)
16611673 """
1674+ if copy is False :
1675+ raise ValueError (
1676+ "Unable to avoid copy while creating an array as requested."
1677+ )
1678+
16621679 ret = take_nd (self .categories ._values , self ._codes )
1663- if dtype and np .dtype (dtype ) != self .categories .dtype :
1664- return np .asarray (ret , dtype )
16651680 # When we're a Categorical[ExtensionArray], like Interval,
16661681 # we need to ensure __array__ gets all the way to an
16671682 # ndarray.
1668- return np .asarray (ret )
1683+
1684+ # `take_nd` should already make a copy, so don't force again.
1685+ return np .asarray (ret , dtype = dtype )
16691686
16701687 def __array_ufunc__ (self , ufunc : np .ufunc , method : str , * inputs , ** kwargs ):
16711688 # for binary ops, use our custom dunder methods
0 commit comments