@@ -577,11 +577,12 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
577
577
raise ValueError ("Cannot convert float NaN to integer" )
578
578
579
579
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 )
585
586
586
587
else :
587
588
# GH8628 (PERF): astype category codes instead of astyping array
@@ -1642,6 +1643,17 @@ def __array__(
1642
1643
"""
1643
1644
The numpy array interface.
1644
1645
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
+
1645
1657
Returns
1646
1658
-------
1647
1659
numpy.array
@@ -1659,13 +1671,18 @@ def __array__(
1659
1671
>>> np.asarray(cat)
1660
1672
array(['a', 'b'], dtype=object)
1661
1673
"""
1674
+ if copy is False :
1675
+ raise ValueError (
1676
+ "Unable to avoid copy while creating an array as requested."
1677
+ )
1678
+
1662
1679
ret = take_nd (self .categories ._values , self ._codes )
1663
- if dtype and np .dtype (dtype ) != self .categories .dtype :
1664
- return np .asarray (ret , dtype )
1665
1680
# When we're a Categorical[ExtensionArray], like Interval,
1666
1681
# we need to ensure __array__ gets all the way to an
1667
1682
# 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 )
1669
1686
1670
1687
def __array_ufunc__ (self , ufunc : np .ufunc , method : str , * inputs , ** kwargs ):
1671
1688
# for binary ops, use our custom dunder methods
0 commit comments