
    h             	         d dl mZ d dlmZ d dlmZ d dlZd dlmZ d dl	m
Z
mZmZmZ d dlZd dlZd dlmZ d dlmZmZmZ d d	lmZ d d
lmZ d dlmZ d dlm Z  d dl!m"Z"m#Z# d dl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ d dl0m1Z1m2Z2m3Z3m4Z4 d dl5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@mAZA d dlBmCZCmDZD d dlEmFZFmGZG d dlHmIZImJZJmKZK d dlLmMc mNZO d dlPmQZQmRZR d dlSmTZT d dlUmVZV d dlWmXZX d dlYmZZZ e
r.d dl[m\Z\m]Z]m^Z^ d dl_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZj d dlkmlZlmmZmmnZn d Zod/d Zp G d! d"eFeKeX      Zq eAeqd#d$gd%&       eAeqg d'd(&       G d) d*e@eKeJ                    Zr	 	 	 	 	 	 d0d+Zs	 d1	 	 	 	 	 d2d,Ztd3d-Zud4d.Zvy)5    )annotations)QUOTE_NONNUMERIC)partialN)get_terminal_size)TYPE_CHECKINGLiteralcastoverload)
get_option)NaTalgoslib)NDArrayBacked)function)find_stack_level)validate_bool_kwarg)coerce_indexer_dtypefind_common_type)ensure_int64ensure_platform_intis_any_real_numeric_dtypeis_bool_dtypeis_dict_likeis_hashableis_integer_dtypeis_list_like	is_scalarneeds_i8_conversionpandas_dtype)
ArrowDtypeCategoricalDtypeCategoricalDtypeTypeExtensionDtype)ABCIndex	ABCSeries)is_valid_na_for_dtypeisna)
algorithms	arraylikeops)PandasDelegatedelegate_names)	factorizetake_nd)NDArrayBackedExtensionArrayravel_compat)ExtensionArrayNoNewAttributesMixinPandasObject)extract_arraysanitize_array)unpack_zerodim_and_defer)nargsort)ObjectStringArrayMixin)console)HashableIteratorSequence)	ArrayLike	AstypeArgAxisIntDtypeDtypeObjNpDtypeOrderedSelfShapeSortKindnpt)	DataFrameIndexSeriesc                     d j                    d t        j                  u t               fd       }|_         |S )N__c                2   t        |      }t        |      r$t        |      t        |       k7  r|st        d      | j                  s
dv rt        d      t        |t              rd}| j                  |      st        |      | j                  sS| j                  j                  |j                        s.t        |j                  |j                  | j                  d      }n|j                  } 	| j                  |      }| j                  dk(  |dk(  z  }|j                         r||<   |S |rc|| j                  v r>| j                  |      } 	| j                  |      }
dvr| j                  dk(  }||<   |S t!        j"                  | |	      S 
d	vrt        d

 dt%        |       d      t        |t&              rt)        |j*                        r	 	||       S  t-        t/        j0                  |       
      t/        j0                  |            S )NzLengths must match.)__lt____gt____le____ge__z7Unordered Categoricals can only compare equality or notz?Categoricals can only be compared if 'categories' are the same.Fcopy>   __eq__rQ   rO   )rU   __ne__z$Cannot compare a Categorical for op z with type zB.
If you want to compare values, use 'np.asarray(cat) <op> other'.)r   r   len
ValueErrorordered	TypeError
isinstanceCategorical#_categories_match_up_to_permutation
categoriesequalsrecode_for_categoriescodes_codesany_unbox_scalarr*   invalid_comparisontyper1   r   dtypegetattrnparray)selfotherhashablemsgother_codesretmaski
fill_valueopopnames           CD:\jyotish\venv\Lib\site-packages\pandas/core/arrays/categorical.pyfuncz_cat_compare_op.<locals>.func~   s   u%3u:T#:8233||AAM  e[) TC;;EBn$<<(>(>u?O?O(P3KK!1!14?? $llT[[+.CKK2%+*;<Dxxz&D	J'&&u-a(!??  ;;",D *CI
--dE2>> 11:6( C K= )88  %05H5U %&27288D>62288E?CC    )__name__operatorner6   )rt   rw   rs   ru   s   ` @@rv   _cat_compare_opr|   z   sK    "++b!Fx{{"Jf%=D &=D~ DMKrx   c                    t        |       	 | j                  j                  |      }t        |      r|v S t        fd|D              S # t        t        f$ r Y yw xY w)aO  
    Helper for membership check for ``key`` in ``cat``.

    This is a helper method for :method:`__contains__`
    and :class:`CategoricalIndex.__contains__`.

    Returns True if ``key`` is in ``cat.categories`` and the
    location of ``key`` in ``categories`` is in ``container``.

    Parameters
    ----------
    cat : :class:`Categorical`or :class:`categoricalIndex`
    key : a hashable object
        The key to check membership for.
    container : Container (e.g. list-like or mapping)
        The container to check for membership in.

    Returns
    -------
    is_in : bool
        True if ``key`` is in ``self.categories`` and location of
        ``key`` in ``categories`` is in ``container``, else False.

    Notes
    -----
    This method does not check for NaN values. Do that separately
    before calling this method.
    Fc              3  &   K   | ]  }|v  
 y wN ).0loc_	containers     rv   	<genexpr>zcontains.<locals>.<genexpr>   s     549$s   )hashr^   get_locKeyErrorrZ   r   rc   )catkeyr   locs     ` rv   containsr      se    : 	I
nn$$S) ~i 5555 i  s   A AAc                  0    e Zd ZU dZdZej                   edg      z  ZdZde	d<   e
	 	 	 	 	 	 de fd       Zdddej                  d	f	 	 	 	 	 	 	 df fd
Zedgd       Zedhd       Ze
ddd	 	 	 	 	 did       Ze
djd       Zedkdld       Zedkdmd       Zedkdnd       Zdodn fdZd Ze
	 dp	 dqd       Ze
	 	 	 	 dr	 	 	 	 	 dsd       Zedtd       Zedud       Zedvd       Zdwdx fdZdydZdzdZdqdZdqd Z d{d|d!Z!dqd"Z"dpdqd#Z#dqd$Z$dqd%Z%dqd&Z&ej                  f	 d}d'Z' e(e)jT                        Z+ e(e)jX                        Z- e(e)j\                        Z/ e(e)j`                        Z1 e(e)jd                        Z3 e(e)jh                        Z5d( Z6d) Z7e
d~d*       Z8e9	 d	 	 	 	 	 dd+       Z:dd,Z;d fd-Z<edhd.       Z=dwdd/Z>dd0Z?e?Z@dd1ZAeAZBdodd2ZCe
	 	 	 	 	 	 dd3       ZDdd4ZEdd5ZFd	d6d7	 	 	 d fd8ZGedddd9	 	 	 	 	 	 	 dd:       ZHeddd;	 	 	 	 	 	 	 dd<       ZHdd	d=d9	 	 	 	 	 	 	 dd>ZHd?d@dAd	ddB	 	 	 	 	 	 	 	 	 ddCZIdvdDZJ	 	 	 	 	 	 	 	 ddEZKedvdF       ZLddGZMdhdHZNddIZOddJZPdwddKZQddLZRddMZSddNZTddOZUdP ZVddQZWd	ddR	 	 	 	 	 d fdSZXd	dTddUZYd	dTddVZZdoddWZ[dq fdXZ\ddZZ]e
ddd[       Z^dd\Z_dd]Z`dd^Zadd_Zbdd`ddaZcej                   edj                   dY      d	f	 ddbZedddcZf	 	 	 	 	 	 	 	 	 	 dddZg xZhS )r\   aZ  
    Represent a categorical variable in classic R / S-plus fashion.

    `Categoricals` can only take on a limited, and usually fixed, number
    of possible values (`categories`). In contrast to statistical categorical
    variables, a `Categorical` might have an order, but numerical operations
    (additions, divisions, ...) are not possible.

    All values of the `Categorical` are either in `categories` or `np.nan`.
    Assigning values outside of `categories` will raise a `ValueError`. Order
    is defined by the order of the `categories`, not lexical order of the
    values.

    Parameters
    ----------
    values : list-like
        The values of the categorical. If categories are given, values not in
        categories will be replaced with NaN.
    categories : Index-like (unique), optional
        The unique categories for this categorical. If not given, the
        categories are assumed to be the unique values of `values` (sorted, if
        possible, otherwise in the order in which they appear).
    ordered : bool, default False
        Whether or not this categorical is treated as a ordered categorical.
        If True, the resulting categorical will be ordered.
        An ordered categorical respects, when sorted, the order of its
        `categories` attribute (which in turn is the `categories` argument, if
        provided).
    dtype : CategoricalDtype
        An instance of ``CategoricalDtype`` to use for this categorical.

    Attributes
    ----------
    categories : Index
        The categories of this categorical.
    codes : ndarray
        The codes (integer positions, which point to the categories) of this
        categorical, read only.
    ordered : bool
        Whether or not this Categorical is ordered.
    dtype : CategoricalDtype
        The instance of ``CategoricalDtype`` storing the ``categories``
        and ``ordered``.

    Methods
    -------
    from_codes
    __array__

    Raises
    ------
    ValueError
        If the categories do not validate.
    TypeError
        If an explicit ``ordered=True`` is given but no `categories` and the
        `values` are not sortable.

    See Also
    --------
    CategoricalDtype : Type for categorical data.
    CategoricalIndex : An Index with an underlying ``Categorical``.

    Notes
    -----
    See the `user guide
    <https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html>`__
    for more.

    Examples
    --------
    >>> pd.Categorical([1, 2, 3, 1, 2, 3])
    [1, 2, 3, 1, 2, 3]
    Categories (3, int64): [1, 2, 3]

    >>> pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'])
    ['a', 'b', 'c', 'a', 'b', 'c']
    Categories (3, object): ['a', 'b', 'c']

    Missing values are not included as a category.

    >>> c = pd.Categorical([1, 2, 3, 1, 2, 3, np.nan])
    >>> c
    [1, 2, 3, 1, 2, 3, NaN]
    Categories (3, int64): [1, 2, 3]

    However, their presence is indicated in the `codes` attribute
    by code `-1`.

    >>> c.codes
    array([ 0,  1,  2,  0,  1,  2, -1], dtype=int8)

    Ordered `Categoricals` can be sorted according to the custom order
    of the categories and can have a min and max value.

    >>> c = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'], ordered=True,
    ...                    categories=['c', 'b', 'a'])
    >>> c
    ['a', 'b', 'c', 'a', 'b', 'c']
    Categories (3, object): ['c' < 'b' < 'a']
    >>> c.min()
    'c'
    i  tolistcategoricalr!   _dtypec                    t        ||j                        }t        d      j                  |      }t        |   ||      S )NFrY   )r   r^   r!   update_dtypesuper_simple_new)clsra   rg   	__class__s      rv   r   zCategorical._simple_newg  s>     %UE,<,<= /<<UCw"5%00rx   NTc                
	   |t         j                  ur%t        j                  dt        t                      nd}t        j                  ||||      }|rBt        ||j                        }t        d      j                  |      }t        | 1  ||       y t        |      st        d      t        j                   d      }t#        |dd       }	t%        |	t              r/|j                  Nt        |j                  |j&                        }n,t%        |t(        t*        t,        f      st/        j0                  |      }t%        |t2              r*t5        |      dk(  rt        j                   g t6              }nt%        |t        j8                        r'|j:                  d	kD  rt=        d
      t?        |d       }nt?        |d       }
tA        |
      }|jC                         rWt        jD                  |       d   D cg c]  }||   	 }}|s|
jF                  dk(  rd }n|
jF                  }t?        |d |      }
|
}|j                  t%        |jF                  tH              rtK        |jF                  jL                  tN              r|jP                  jS                         }
|
jT                  jW                  tH              }|
jX                  j[                         }t        ||jF                  j\                  j&                        }nt%        |t(              st?        |d       }	 t_        |d      \  }}t        ||j&                        }nst%        |jF                  t              rCta        |      jb                  }te        ||jF                  j                  |j                  |      }ntg        ||j                        }|jC                         r4t        jh                  |jj                  |jF                         }||| <   |}t        d      j                  |      }t        ||j                        }
t        | 1  |
|       y c c}w # t        $ r3}t_        |d      \  }}|j&                  rt        d      |Y d }~Ld }~ww xY w)NzThe 'fastpath' keyword in Categorical is deprecated and will be removed in a future version. Use Categorical.from_codes instead
stacklevelFr   z#Categorical input must be list-likerg   r   rg      z3> 1 ndim Categorical are not supported at this timeobject)types_mapperTsortzl'values' is not ordered, please explicitly specify the categories order by passing in a categories argument.rR   )6r   
no_defaultwarningswarnDeprecationWarningr   r!   _from_values_or_dtyper   r^   r   r   __init__r   rZ   ri   rj   rh   r[   rY   r$   r%   r1   comconvert_to_list_likelistrW   r   ndarrayndimNotImplementedErrorr5   r'   rc   whererg   r    
issubclassrf   r"   	_pa_arraycombine_chunks
dictionary	to_pandasindicesto_numpypyarrow_dtyper-   r4   rb   r`   _get_codes_for_valuesonesshape)rk   valuesr^   rY   rg   fastpathrS   ra   	null_maskvdtypearridxarr_listsanitize_dtypeerr	old_codes
full_codesr   s                    rv   r   zCategorical.__init__s  s    3>>)MMU"+-	 H 66J
 (1A1ABE$U3@@GEGUE*F#ABB HHUO	 $/f./'():):EMMJFXy.$IJ--f5F&$'CK1,<"F3FBJJ/;;?-M  (5 %VT2 I	==? 8:xx
7KA7NO7Ns7NHO  399#8)-),(4~NC#&,,
3
!!#79 &&557 ^^55:5N
,,.(V\\5O5O5W5WX!&(3+FD9F#(1&t(D%E: )U]]C&67%f-44I)6<<22E4D4D4E
 *&%2B2BCE==?'')//EEJ%*J	z"E /<<UC"5%*:*:;e$q  P2 ! 	#(1&u(E%E:}} (C  #	# %	#s   <Q!Q 	R(Q==Rc                    | j                   S )an  
        The :class:`~pandas.api.types.CategoricalDtype` for this instance.

        Examples
        --------
        >>> cat = pd.Categorical(['a', 'b'], ordered=True)
        >>> cat
        ['a', 'b']
        Categories (2, object): ['a' < 'b']
        >>> cat.dtype
        CategoricalDtype(categories=['a', 'b'], ordered=True, categories_dtype=object)
        )r   rk   s    rv   rg   zCategorical.dtype  s     {{rx   c                P    | j                   j                  }|j                  d      S NrT   )_ndarrayrg   rf   )rk   rg   s     rv   _internal_fill_valuez Categorical._internal_fill_value  s!     ##zz"~rx   Frg   rS   c                    | |||      S )Nr   r   )r   scalarsrg   rS   s       rv   _from_sequencezCategorical._from_sequence  s     7%d33rx   c                   |t         | j                  ||      }t        |      }||j                         k(  j                         st        |S )Nr   )r   r   r'   allrX   )r   r   rg   resrq   s        rv   _from_scalarszCategorical._from_scalars  sO    =%%   6 G}
"'')
rx   .c                     y r   r   rk   rg   rS   s      rv   astypezCategorical.astype      rx   c                     y r   r   r   s      rv   r   zCategorical.astype  r   rx   c                     y r   r   r   s      rv   r   zCategorical.astype#  r   rx   c                j   t        |      }| j                  |u r|r| j                         }|S | }|S t        |t              rB| j                  j                  |      }|r| j                         n| } | j                  |      }|S t        |t              rt        | %  ||      S |j                  dv r)| j                         j                         rt        d      t        | j                        dk(  st        | j                         dk(  r4|st#        j$                  | |      }|S t#        j&                  | |      }|S | j                   j(                  }	 |j                  ||      }| j                   j*                  }t-        ||      sKt/        j0                  t#        j&                  | j                   j*                        j                  |            }t5        |t7        | j8                        |	      }|S # t2        t        f$ r( d| j                   j                   d| }t        |      w xY w)
aZ  
        Coerce this type to another dtype

        Parameters
        ----------
        dtype : numpy dtype or pandas type
        copy : bool, default True
            By default, astype always returns a newly allocated object.
            If copy is set to False and dtype is categorical, the original
            object is returned.
        rR   iuz#Cannot convert float NaN to integerr   r   r   zCannot cast z
 dtype to rs   )r   rg   rS   r[   r!   r   
_set_dtyper#   r   r   kindr'   rc   rX   rW   ra   r^   ri   asarrayrj   _values	_na_valuer&   r   item_from_zerodimrZ   r.   r   rb   )rk   rg   rS   resultnew_catsrs   rn   r   s          rv   r   zCategorical.astype'  s    U#::$(TYY[FX Y /3FX U /0JJ++E2E"&499;DD__U+FL I ~.7>%d>33ZZ4DIIKOO$5BCC_!S%9Q%> D64 1 $e40 ) ..H&#??T?B!__66
,Z?!$!6!6!:!:;BB5I"J -dkk:zF   & %T__%:%:$;:eWM o%&s   B G; ;7H2c                j    t        j                  dt        t                      | j	                         S )z#
        Alias for tolist.
        zcCategorical.to_list is deprecated and will be removed in a future version. Use obj.tolist() insteadr   )r   r   FutureWarningr   r   r   s    rv   to_listzCategorical.to_listc  s,    
 	0')		
 {{}rx   c                   ddl m}m}m}m}  ||      }	t        |t              xr |j                  du}
|
rt        |j                  j                        r ||d      }	nt        j                  |j                  j                  d      r ||d      }	nkt        j                  |j                  j                  d      r ||d      }	n6t        |j                  j                        r|g d}|	j                  |      }	|
r|j                  }t        ||	|      }nV|	j                  s;|	j!                         }|	j#                         }t        |||      }t        |d	
      }nt        |	d	
      }|}| j%                  ||      S )aA  
        Construct a Categorical from inferred values.

        For inferred categories (`dtype` is None) the categories are sorted.
        For explicit `dtype`, the `inferred_categories` are cast to the
        appropriate type.

        Parameters
        ----------
        inferred_categories : Index
        inferred_codes : Index
        dtype : CategoricalDtype or 'category'
        true_values : list, optional
            If none are provided, the default ones are
            "True", "TRUE", and "true."

        Returns
        -------
        Categorical
        r   )rI   to_datetime
to_numericto_timedeltaNcoerce)errorsMm)TrueTRUEtrueFr   r   )pandasrI   r   r   r   r[   r!   r^   r   rg   r   is_np_dtyper   isinr`   is_monotonic_increasingrS   sort_valuesr   )r   inferred_categoriesinferred_codesrg   true_valuesrI   r   r   r   catsknown_categoriesr^   ra   unsorteds                 rv   _from_inferred_categoriesz%Categorical._from_inferred_categoriesp  sX   0	
 	
 ()u./PE4D4DD4P 	 ()9)9)?)?@!"5hG!1!1!7!7="#6xH!1!1!7!7=#$7Iu//556&":K yy-))J).$
KE--yy{H))+J).(JOE$Z?E$T59E"EuE22rx   c                    t        j                  |||      }|j                  d}t        |      |r| j	                  ||      }| j                  ||      S )a  
        Make a Categorical type from codes and categories or dtype.

        This constructor is useful if you already have codes and
        categories/dtype and so do not need the (computation intensive)
        factorization step, which is usually done on the constructor.

        If your data does not follow this convention, please use the normal
        constructor.

        Parameters
        ----------
        codes : array-like of int
            An integer array, where each integer points to a category in
            categories or dtype.categories, or else is -1 for NaN.
        categories : index-like, optional
            The categories for the categorical. Items need to be unique.
            If the categories are not given here, then they must be provided
            in `dtype`.
        ordered : bool, optional
            Whether or not this categorical is treated as an ordered
            categorical. If not given here or in `dtype`, the resulting
            categorical will be unordered.
        dtype : CategoricalDtype or "category", optional
            If :class:`CategoricalDtype`, cannot be used together with
            `categories` or `ordered`.
        validate : bool, default True
            If True, validate that the codes are valid for the dtype.
            If False, don't validate that the codes are valid. Be careful about skipping
            validation, as invalid codes can lead to severe problems, such as segfaults.

            .. versionadded:: 2.1.0

        Returns
        -------
        Categorical

        Examples
        --------
        >>> dtype = pd.CategoricalDtype(['a', 'b'], ordered=True)
        >>> pd.Categorical.from_codes(codes=[0, 1, 0, 1], dtype=dtype)
        ['a', 'b', 'a', 'b']
        Categories (2, object): ['a' < 'b']
        )r^   rY   rg   zKThe categories must be provided in 'categories' or 'dtype'. Both were None.r   )r!   r   r^   rX   _validate_codes_for_dtyper   )r   ra   r^   rY   rg   validatern   s          rv   
from_codeszCategorical.from_codes  sk    j !66!7%
 #+  S/!11%u1EEuE22rx   c                .    | j                   j                  S )a]  
        The categories of this categorical.

        Setting assigns new values to each category (effectively a rename of
        each individual category).

        The assigned value has to be a list-like object. All items must be
        unique and the number of items in the new categories must be the same
        as the number of items in the old categories.

        Raises
        ------
        ValueError
            If the new categories do not validate as categories or if the
            number of new categories is unequal the number of old categories

        See Also
        --------
        rename_categories : Rename categories.
        reorder_categories : Reorder categories.
        add_categories : Add new categories.
        remove_categories : Remove the specified categories.
        remove_unused_categories : Remove categories which are not used.
        set_categories : Set the categories to the specified ones.

        Examples
        --------
        For :class:`pandas.Series`:

        >>> ser = pd.Series(['a', 'b', 'c', 'a'], dtype='category')
        >>> ser.cat.categories
        Index(['a', 'b', 'c'], dtype='object')

        >>> raw_cat = pd.Categorical(['a', 'b', 'c', 'a'], categories=['b', 'c', 'd'])
        >>> ser = pd.Series(raw_cat)
        >>> ser.cat.categories
        Index(['b', 'c', 'd'], dtype='object')

        For :class:`pandas.Categorical`:

        >>> cat = pd.Categorical(['a', 'b'], ordered=True)
        >>> cat.categories
        Index(['a', 'b'], dtype='object')

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'c', 'b', 'a', 'c', 'b'])
        >>> ci.categories
        Index(['a', 'b', 'c'], dtype='object')

        >>> ci = pd.CategoricalIndex(['a', 'c'], categories=['c', 'b', 'a'])
        >>> ci.categories
        Index(['c', 'b', 'a'], dtype='object')
        )rg   r^   r   s    rv   r^   zCategorical.categories  s    p zz$$$rx   c                .    | j                   j                  S )a{  
        Whether the categories have an ordered relationship.

        Examples
        --------
        For :class:`pandas.Series`:

        >>> ser = pd.Series(['a', 'b', 'c', 'a'], dtype='category')
        >>> ser.cat.ordered
        False

        >>> raw_cat = pd.Categorical(['a', 'b', 'c', 'a'], ordered=True)
        >>> ser = pd.Series(raw_cat)
        >>> ser.cat.ordered
        True

        For :class:`pandas.Categorical`:

        >>> cat = pd.Categorical(['a', 'b'], ordered=True)
        >>> cat.ordered
        True

        >>> cat = pd.Categorical(['a', 'b'], ordered=False)
        >>> cat.ordered
        False

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'b'], ordered=True)
        >>> ci.ordered
        True

        >>> ci = pd.CategoricalIndex(['a', 'b'], ordered=False)
        >>> ci.ordered
        False
        )rg   rY   r   s    rv   rY   zCategorical.ordered7  s    L zz!!!rx   c                \    | j                   j                         }d|j                  _        |S )a  
        The category codes of this categorical index.

        Codes are an array of integers which are the positions of the actual
        values in the categories array.

        There is no setter, use the other categorical methods and the normal item
        setter to change values in the categorical.

        Returns
        -------
        ndarray[int]
            A non-writable view of the ``codes`` array.

        Examples
        --------
        For :class:`pandas.Categorical`:

        >>> cat = pd.Categorical(['a', 'b'], ordered=True)
        >>> cat.codes
        array([0, 1], dtype=int8)

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'a', 'b', 'c'])
        >>> ci.codes
        array([0, 1, 2, 0, 1, 2], dtype=int8)

        >>> ci = pd.CategoricalIndex(['a', 'c'], categories=['c', 'b', 'a'])
        >>> ci.codes
        array([2, 0], dtype=int8)
        F)rb   viewflags	writeable)rk   vs     rv   ra   zCategorical.codes_  s(    D KK!rx   c                ^   |r!t        j                  || j                        }nt        || j                        }|sV| j                  j                  @t        |j                        t        | j                  j                        k7  rt        d      t        | !  | j                  |       y)a  
        Sets new categories inplace

        Parameters
        ----------
        fastpath : bool, default False
           Don't perform validation of the categories for uniqueness or nulls

        Examples
        --------
        >>> c = pd.Categorical(['a', 'b'])
        >>> c
        ['a', 'b']
        Categories (2, object): ['a', 'b']

        >>> c._set_categories(pd.Index(['a', 'c']))
        >>> c
        ['a', 'c']
        Categories (2, object): ['a', 'c']
        r   NzKnew categories need to have the same number of items as the old categories!)
r!   _from_fastpathrY   rg   r^   rW   rX   r   r   r   )rk   r^   r   	new_dtyper   s       rv   _set_categorieszCategorical._set_categories  s    * (77
DLLQI(T\\JI

%%1I(()S1F1F-GG/ 
 		2rx   c                    t        | j                  | j                  |j                        }t        |       j	                  ||      S )a+  
        Internal method for directly updating the CategoricalDtype

        Parameters
        ----------
        dtype : CategoricalDtype

        Notes
        -----
        We don't do any validation here. It's assumed that the dtype is
        a (valid) instance of `CategoricalDtype`.
        r   )r`   ra   r^   rf   r   )rk   rg   ra   s      rv   r   zCategorical._set_dtype  s:     &djj$//5CSCSTDz%%e5%99rx   c                    t        | j                  |      }| j                         }t        j                  ||j
                  |       |S )z
        Set the ordered attribute to the boolean value.

        Parameters
        ----------
        value : bool
           Set whether this categorical is ordered (True) or not (False).
        r   )r!   r^   rS   r   r   r   )rk   valuer	  r   s       rv   set_orderedzCategorical.set_ordered  s:     %T__eD	iiksCLL)<
rx   c                $    | j                  d      S )ae  
        Set the Categorical to be ordered.

        Returns
        -------
        Categorical
            Ordered Categorical.

        Examples
        --------
        For :class:`pandas.Series`:

        >>> ser = pd.Series(['a', 'b', 'c', 'a'], dtype='category')
        >>> ser.cat.ordered
        False
        >>> ser = ser.cat.as_ordered()
        >>> ser.cat.ordered
        True

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'a'])
        >>> ci.ordered
        False
        >>> ci = ci.as_ordered()
        >>> ci.ordered
        True
        Tr  r   s    rv   
as_orderedzCategorical.as_ordered  s    : %%rx   c                $    | j                  d      S )a  
        Set the Categorical to be unordered.

        Returns
        -------
        Categorical
            Unordered Categorical.

        Examples
        --------
        For :class:`pandas.Series`:

        >>> raw_cat = pd.Categorical(['a', 'b', 'c', 'a'], ordered=True)
        >>> ser = pd.Series(raw_cat)
        >>> ser.cat.ordered
        True
        >>> ser = ser.cat.as_unordered()
        >>> ser.cat.ordered
        False

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'a'], ordered=True)
        >>> ci.ordered
        True
        >>> ci = ci.as_unordered()
        >>> ci.ordered
        False
        Fr  r   s    rv   as_unorderedzCategorical.as_unordered  s    < &&rx   c                   || j                   j                  }t        ||      }| j                         }|r|j                   j                  dt        |j                        t        |j                   j                        k  r/d|j                  |j                  t        |j                        k\  <   |j                  }n+t        |j                  |j                  |j                        }t        j                  |||       |S )a  
        Set the categories to the specified new categories.

        ``new_categories`` can include new categories (which will result in
        unused categories) or remove old categories (which results in values
        set to ``NaN``). If ``rename=True``, the categories will simply be renamed
        (less or more items than in old categories will result in values set to
        ``NaN`` or in unused categories respectively).

        This method can be used to perform more than one action of adding,
        removing, and reordering simultaneously and is therefore faster than
        performing the individual steps via the more specialised methods.

        On the other hand this methods does not do checks (e.g., whether the
        old categories are included in the new categories on a reorder), which
        can result in surprising changes, for example when using special string
        dtypes, which does not considers a S1 string equal to a single char
        python string.

        Parameters
        ----------
        new_categories : Index-like
           The categories in new order.
        ordered : bool, default False
           Whether or not the categorical is treated as a ordered categorical.
           If not given, do not change the ordered information.
        rename : bool, default False
           Whether or not the new_categories should be considered as a rename
           of the old categories or as reordered categories.

        Returns
        -------
        Categorical with reordered categories.

        Raises
        ------
        ValueError
            If new_categories does not validate as categories

        See Also
        --------
        rename_categories : Rename categories.
        reorder_categories : Reorder categories.
        add_categories : Add new categories.
        remove_categories : Remove the specified categories.
        remove_unused_categories : Remove categories which are not used.

        Examples
        --------
        For :class:`pandas.Series`:

        >>> raw_cat = pd.Categorical(['a', 'b', 'c', 'A'],
        ...                           categories=['a', 'b', 'c'], ordered=True)
        >>> ser = pd.Series(raw_cat)
        >>> ser
        0   a
        1   b
        2   c
        3   NaN
        dtype: category
        Categories (3, object): ['a' < 'b' < 'c']

        >>> ser.cat.set_categories(['A', 'B', 'C'], rename=True)
        0   A
        1   B
        2   C
        3   NaN
        dtype: category
        Categories (3, object): ['A' < 'B' < 'C']

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'A'],
        ...                          categories=['a', 'b', 'c'], ordered=True)
        >>> ci
        CategoricalIndex(['a', 'b', 'c', nan], categories=['a', 'b', 'c'],
                         ordered=True, dtype='category')

        >>> ci.set_categories(['A', 'b', 'c'])
        CategoricalIndex([nan, 'b', 'c', nan], categories=['A', 'b', 'c'],
                         ordered=True, dtype='category')
        >>> ci.set_categories(['A', 'b', 'c'], rename=True)
        CategoricalIndex(['A', 'b', 'c', nan], categories=['A', 'b', 'c'],
                         ordered=True, dtype='category')
        r   rT   )rg   rY   r!   rS   r^   rW   rb   r`   ra   r   r   )rk   new_categoriesrY   renamer	  r   ra   s          rv   set_categorieszCategorical.set_categories  s    n ?jj((G$^WE	iikyy##/C	8L8L4MPS		$$Q 5 GI

3::Y-A-A)BBCJJE)		3>>9+?+?E 	sE95
rx   c                   t        |      r*| j                  D cg c]  }|j                  ||       }}n*t        |      r| j                  D cg c]
  } ||       }}| j	                         }|j                  |       |S c c}w c c}w )a  
        Rename categories.

        Parameters
        ----------
        new_categories : list-like, dict-like or callable

            New categories which will replace old categories.

            * list-like: all items must be unique and the number of items in
              the new categories must match the existing number of categories.

            * dict-like: specifies a mapping from
              old categories to new. Categories not contained in the mapping
              are passed through and extra categories in the mapping are
              ignored.

            * callable : a callable that is called on all items in the old
              categories and whose return values comprise the new categories.

        Returns
        -------
        Categorical
            Categorical with renamed categories.

        Raises
        ------
        ValueError
            If new categories are list-like and do not have the same number of
            items than the current categories or do not validate as categories

        See Also
        --------
        reorder_categories : Reorder categories.
        add_categories : Add new categories.
        remove_categories : Remove the specified categories.
        remove_unused_categories : Remove categories which are not used.
        set_categories : Set the categories to the specified ones.

        Examples
        --------
        >>> c = pd.Categorical(['a', 'a', 'b'])
        >>> c.rename_categories([0, 1])
        [0, 0, 1]
        Categories (2, int64): [0, 1]

        For dict-like ``new_categories``, extra keys are ignored and
        categories not in the dictionary are passed through

        >>> c.rename_categories({'a': 'A', 'c': 'C'})
        ['A', 'A', 'b']
        Categories (2, object): ['A', 'b']

        You may also provide a callable to create the new categories

        >>> c.rename_categories(lambda x: x.upper())
        ['A', 'A', 'B']
        Categories (2, object): ['A', 'B']
        )r   r^   getcallablerS   r
  )rk   r  itemr   s       rv   rename_categorieszCategorical.rename_categoriesq  s    z ';???;J4""4.?   n%?COtnT2NOiikN+
 Ps   BBc                    t        | j                        t        |      k7  s%| j                  j                  |      j                  st	        d      | j                  ||      S )a  
        Reorder categories as specified in new_categories.

        ``new_categories`` need to include all old categories and no new category
        items.

        Parameters
        ----------
        new_categories : Index-like
           The categories in new order.
        ordered : bool, optional
           Whether or not the categorical is treated as a ordered categorical.
           If not given, do not change the ordered information.

        Returns
        -------
        Categorical
            Categorical with reordered categories.

        Raises
        ------
        ValueError
            If the new categories do not contain all old category items or any
            new ones

        See Also
        --------
        rename_categories : Rename categories.
        add_categories : Add new categories.
        remove_categories : Remove the specified categories.
        remove_unused_categories : Remove categories which are not used.
        set_categories : Set the categories to the specified ones.

        Examples
        --------
        For :class:`pandas.Series`:

        >>> ser = pd.Series(['a', 'b', 'c', 'a'], dtype='category')
        >>> ser = ser.cat.reorder_categories(['c', 'b', 'a'], ordered=True)
        >>> ser
        0   a
        1   b
        2   c
        3   a
        dtype: category
        Categories (3, object): ['c' < 'b' < 'a']

        >>> ser.sort_values()
        2   c
        1   b
        0   a
        3   a
        dtype: category
        Categories (3, object): ['c' < 'b' < 'a']

        For :class:`pandas.CategoricalIndex`:

        >>> ci = pd.CategoricalIndex(['a', 'b', 'c', 'a'])
        >>> ci
        CategoricalIndex(['a', 'b', 'c', 'a'], categories=['a', 'b', 'c'],
                         ordered=False, dtype='category')
        >>> ci.reorder_categories(['c', 'b', 'a'], ordered=True)
        CategoricalIndex(['a', 'b', 'c', 'a'], categories=['c', 'b', 'a'],
                         ordered=True, dtype='category')
        z=items in new_categories are not the same as in old categoriesr   )rW   r^   
differenceemptyrX   r  )rk   r  rY   s      rv   reorder_categorieszCategorical.reorder_categories  s[    F  C$77??--n=CCO  "">7"CCrx   c                   t        |      s|g}t        |      t        | j                  j                        z  }t	        |      dk7  rt        d|       t        |d      roddlm} t        | j                  j                  j                  |j                  g      } |t        | j                  j                        t        |      z   |      }n+t        | j                  j                        t        |      z   }t        || j                        }| j                         }t        |j                  |j                        }t!        j"                  |||       |S )a  
        Add new categories.

        `new_categories` will be included at the last/highest place in the
        categories and will be unused directly after this call.

        Parameters
        ----------
        new_categories : category or list-like of category
           The new categories to be included.

        Returns
        -------
        Categorical
            Categorical with new categories added.

        Raises
        ------
        ValueError
            If the new categories include old categories or do not validate as
            categories

        See Also
        --------
        rename_categories : Rename categories.
        reorder_categories : Reorder categories.
        remove_categories : Remove the specified categories.
        remove_unused_categories : Remove categories which are not used.
        set_categories : Set the categories to the specified ones.

        Examples
        --------
        >>> c = pd.Categorical(['c', 'b', 'c'])
        >>> c
        ['c', 'b', 'c']
        Categories (2, object): ['b', 'c']

        >>> c.add_categories(['d', 'a'])
        ['c', 'b', 'c']
        Categories (4, object): ['b', 'c', 'd', 'a']
        r   z0new categories must not include old categories: rg   rJ   r   )r   setrg   r^   rW   rX   hasattrr   rJ   r   r   r!   rY   rS   r   r   r   r   )rk   r  already_includedrJ   rg   r	  r   ra   s           rv   add_categorieszCategorical.add_categories  s$   V N+,-N~.TZZ5J5J1KK A%BCSBTU  >7+%$&&,,n.B.BCE $TZZ**+d>.BB%N "$**"7"784;OON$^T\\B	iik$S\\93G3GHsE95
rx   c                   ddl m} t        |      s|g} ||      j                         j	                         }| j
                  j                  du r'| j
                  j                  j                  |d      n$| j
                  j                  j                  |      }|j                  | j
                  j                        }t        |      dk7  rt        |      }t        d|       | j                  || j                  d      S )a  
        Remove the specified categories.

        `removals` must be included in the old categories. Values which were in
        the removed categories will be set to NaN

        Parameters
        ----------
        removals : category or list of categories
           The categories which should be removed.

        Returns
        -------
        Categorical
            Categorical with removed categories.

        Raises
        ------
        ValueError
            If the removals are not contained in the categories

        See Also
        --------
        rename_categories : Rename categories.
        reorder_categories : Reorder categories.
        add_categories : Add new categories.
        remove_unused_categories : Remove categories which are not used.
        set_categories : Set the categories to the specified ones.

        Examples
        --------
        >>> c = pd.Categorical(['a', 'c', 'b', 'c', 'd'])
        >>> c
        ['a', 'c', 'b', 'c', 'd']
        Categories (4, object): ['a', 'b', 'c', 'd']

        >>> c.remove_categories(['d', 'a'])
        [NaN, 'c', 'b', 'c', NaN]
        Categories (2, object): ['b', 'c']
        r   rI   TFr   z(removals must all be in old categories: )rY   r  )r   rI   r   uniquedropnarg   rY   r^   r  rW   r#  rX   r  )rk   removalsrI   r  not_includeds        rv   remove_categorieszCategorical.remove_categoriesI  s    R 	!H% zH?))+224 zz!!T) JJ!!,,XE,B&&11(; 	
  **4::+@+@A|!|,LG~VWW"">4<<PU"VVrx   c                   t        j                  | j                  d      \  }}|j                  dk7  r|d   dk(  r
|dd |dz
  }}| j                  j
                  j                  |      }t        j                  || j                        }t        ||j
                        }| j                         }t        j                  |||       |S )a  
        Remove categories which are not used.

        Returns
        -------
        Categorical
            Categorical with unused categories dropped.

        See Also
        --------
        rename_categories : Rename categories.
        reorder_categories : Reorder categories.
        add_categories : Add new categories.
        remove_categories : Remove the specified categories.
        set_categories : Set the categories to the specified ones.

        Examples
        --------
        >>> c = pd.Categorical(['a', 'c', 'b', 'c', 'd'])
        >>> c
        ['a', 'c', 'b', 'c', 'd']
        Categories (4, object): ['a', 'b', 'c', 'd']

        >>> c[2] = 'a'
        >>> c[4] = 'c'
        >>> c
        ['a', 'c', 'a', 'c', 'c']
        Categories (4, object): ['a', 'b', 'c', 'd']

        >>> c.remove_unused_categories()
        ['a', 'c', 'a', 'c', 'c']
        Categories (2, object): ['a', 'c']
        T)return_inverser   rT   r   Nr   )ri   r)  rb   sizerg   r^   taker!   r  rY   r   rS   r   r   )rk   r   invr  r	  	new_codesr   s          rv   remove_unused_categoriesz$Categorical.remove_unused_categories  s    D 99T[[>S88q=SVr\12waC..33C8$33DLL
	 )i.B.BC	iiksIy9
rx   c                6   |t         j                  u r&t        j                  dt        t                      d}t        |      st        |      sJ | j                  j                  |      }t        j                  | j                  dk(        }t        j                  }|Q|rOt        |      r |t        j                        n-|j                  t        j                  t        j                        }|j                  ra|j                   sU|t        j                  u rCt#        || j$                        }| j'                  | j                  j)                         |d      S |r|j+                  t-        |      |      }t        j.                  || j                        S )a  
        Map categories using an input mapping or function.

        Maps the categories to new categories. If the mapping correspondence is
        one-to-one the result is a :class:`~pandas.Categorical` which has the
        same order property as the original, otherwise a :class:`~pandas.Index`
        is returned. NaN values are unaffected.

        If a `dict` or :class:`~pandas.Series` is used any unmapped category is
        mapped to `NaN`. Note that if this happens an :class:`~pandas.Index`
        will be returned.

        Parameters
        ----------
        mapper : function, dict, or Series
            Mapping correspondence.
        na_action : {None, 'ignore'}, default 'ignore'
            If 'ignore', propagate NaN values, without passing them to the
            mapping correspondence.

            .. deprecated:: 2.1.0

               The default value of 'ignore' has been deprecated and will be changed to
               None in the future.

        Returns
        -------
        pandas.Categorical or pandas.Index
            Mapped categorical.

        See Also
        --------
        CategoricalIndex.map : Apply a mapping correspondence on a
            :class:`~pandas.CategoricalIndex`.
        Index.map : Apply a mapping correspondence on an
            :class:`~pandas.Index`.
        Series.map : Apply a mapping correspondence on a
            :class:`~pandas.Series`.
        Series.apply : Apply more complex functions on a
            :class:`~pandas.Series`.

        Examples
        --------
        >>> cat = pd.Categorical(['a', 'b', 'c'])
        >>> cat
        ['a', 'b', 'c']
        Categories (3, object): ['a', 'b', 'c']
        >>> cat.map(lambda x: x.upper(), na_action=None)
        ['A', 'B', 'C']
        Categories (3, object): ['A', 'B', 'C']
        >>> cat.map({'a': 'first', 'b': 'second', 'c': 'third'}, na_action=None)
        ['first', 'second', 'third']
        Categories (3, object): ['first', 'second', 'third']

        If the mapping is one-to-one the ordering of the categories is
        preserved:

        >>> cat = pd.Categorical(['a', 'b', 'c'], ordered=True)
        >>> cat
        ['a', 'b', 'c']
        Categories (3, object): ['a' < 'b' < 'c']
        >>> cat.map({'a': 3, 'b': 2, 'c': 1}, na_action=None)
        [3, 2, 1]
        Categories (3, int64): [3 < 2 < 1]

        If the mapping is not one-to-one an :class:`~pandas.Index` is returned:

        >>> cat.map({'a': 'first', 'b': 'second', 'c': 'first'}, na_action=None)
        Index(['first', 'second', 'first'], dtype='object')

        If a `dict` is used, all unmapped categories are mapped to `NaN` and
        the result is an :class:`~pandas.Index`:

        >>> cat.map({'a': 'first', 'b': 'second'}, na_action=None)
        Index(['first', 'second', nan], dtype='object')
        zThe default value of 'ignore' for the `na_action` parameter in pandas.Categorical.map is deprecated and will be changed to 'None' in a future version. Please set na_action to the desired value to avoid seeing this warningr   ignorerT   r   Frg   r   )r   r   r   r   r   r   r  r   r^   mapri   rc   rb   nanr  	is_uniquehasnansr!   rY   r   rS   insertrW   r1  )rk   mapper	na_actionr  has_nansna_valr	  s          rv   r8  zCategorical.map  s2   b &MM= +- !I<#777,,V466$+++,'/'7VBFF^VZZPRPVPV=WF##N,B,BvQSQWQWGW(NI??4;;#3#3#5YQV?WW+223~3FONww~t{{33rx   c                \    t        |      s| j                  |      S | j                  |      S r   )r   _validate_listlike_validate_scalar)rk   r  s     rv   _validate_setitem_valuez#Categorical._validate_setitem_value1  s,    5!**511((//rx   c                    t        || j                  j                        rd}|S || j                  v r| j                  |      }|S t	        d| d      d)aK  
        Convert a user-facing fill_value to a representation to use with our
        underlying ndarray, raising TypeError if this is not possible.

        Parameters
        ----------
        fill_value : object

        Returns
        -------
        fill_value : int

        Raises
        ------
        TypeError
        rT   z5Cannot setitem on a Categorical with a new category (z), set the categories firstN)r&   r^   rg   rd   rZ   )rk   rs   s     rv   rC  zCategorical._validate_scalar8  sr    $ !T__-B-BCJ  4??*++J7J 	 'L(CE rx   c                  t        |t              rZt        |j                        rEt	        |      j                         rt        d      |j                  t        j                        }nt        j                  |      }t        |      r#|j                  j                  dvrt        d      t        |      rD|j                         t        |j                        k\  s|j                         dk  rt        d      |S )Nzcodes cannot contain NA valuesr   r   z$codes need to be array-like integersrT   z1codes need to be between -1 and len(categories)-1)r[   r1   r   rg   r'   rc   rX   r   ri   int64r   rW   r   maxr^   min)r   ra   rg   s      rv   r   z%Categorical._validate_codes_for_dtypeU  s    e^,1A%++1NE{  !ABBNNN2EJJu%Eu:%++**$6CDDu:599;#e.>.>*??599;QSCSPQQrx   c                    |du r$t        j                  dt        t                      t	        | j
                  j                  | j                        }t        j                  ||      S )a  
        The numpy array interface.

        Users should not call this directly. Rather, it is invoked by
        :func:`numpy.array` and :func:`numpy.asarray`.

        Parameters
        ----------
        dtype : np.dtype or None
            Specifies the the dtype for the array.

        copy : bool or None, optional
            See :func:`numpy.asarray`.

        Returns
        -------
        numpy.array
            A numpy array of either the specified dtype or,
            if dtype==None (default), the same dtype as
            categorical.categories.dtype.

        Examples
        --------

        >>> cat = pd.Categorical(['a', 'b'], ordered=True)

        The following calls ``cat.__array__``

        >>> np.asarray(cat)
        array(['a', 'b'], dtype=object)
        FaS  Starting with NumPy 2.0, the behavior of the 'copy' keyword has changed and passing 'copy=False' raises an error when returning a zero-copy NumPy array is not possible. pandas will follow this behavior starting with pandas 3.0.
This conversion to NumPy requires a copy, but 'copy=False' was passed. Consider using 'np.asarray(..)' instead.r   r   )
r   r   r   r   r.   r^   r   rb   ri   r   )rk   rg   rS   rp   s       rv   	__array__zCategorical.__array__g  sW    F 5=MM2 +-	 doo--t{{; zz#U++rx   c                (   t        j                  | ||g|i |}|t        ur|S d|v rt        j                  | ||g|i |S |dk(  r%t        j                  | ||g|i |}|t        ur|S t        d| j                   d|j                         )NoutreducezObject with dtype z cannot perform the numpy op )r)   !maybe_dispatch_ufunc_to_dunder_opNotImplementeddispatch_ufunc_with_outdispatch_reduction_ufuncrZ   rg   ry   )rk   ufuncmethodinputskwargsr   s         rv   __array_ufunc__zCategorical.__array_ufunc__  s    <<%
"(
,2
 'MF?44eV&,06  X77eV&,06F ^+   -!NN+-
 	
rx   c                    t        |t              st        |   |      S d|vrt	        |d   |d         |d<   d|v rd|vr|j                  d      |d<   t        |   |       y)z*Necessary for making this object picklabler   _categories_orderedrb   r   N)r[   dictr   __setstate__r!   pop)rk   stater   s     rv   r\  zCategorical.__setstate__  sn    %&7'..5 .u]/CU:EVWE(Ou5!8 %		( 3E*U#rx   c                    | j                   j                  | j                  j                  j                  j                  z   S r   )rb   nbytesrg   r^   r   r   s    rv   r`  zCategorical.nbytes  s-    {{!!DJJ$9$9$@$@$G$GGGrx   c                |    | j                   j                  | j                  j                  j	                  |      z   S )a  
        Memory usage of my values

        Parameters
        ----------
        deep : bool
            Introspect the data deeply, interrogate
            `object` dtypes for system-level memory consumption

        Returns
        -------
        bytes used

        Notes
        -----
        Memory usage does not include memory consumed by elements that
        are not components of the array if deep=False

        See Also
        --------
        numpy.ndarray.nbytes
        )deep)rb   r`  rg   r^   memory_usage)rk   rb  s     rv   rc  zCategorical.memory_usage  s1    . {{!!DJJ$9$9$F$FD$F$QQQrx   c                     | j                   dk(  S )aX  
        Detect missing values

        Missing values (-1 in .codes) are detected.

        Returns
        -------
        np.ndarray[bool] of whether my values are null

        See Also
        --------
        isna : Top-level isna.
        isnull : Alias of isna.
        Categorical.notna : Boolean inverse of Categorical.isna.

        rT   )rb   r   s    rv   r'   zCategorical.isna  s    " {{b  rx   c                $    | j                          S )a  
        Inverse of isna

        Both missing values (-1 in .codes) and NA as a category are detected as
        null.

        Returns
        -------
        np.ndarray[bool] of whether my values are not null

        See Also
        --------
        notna : Top-level notna.
        notnull : Alias of notna.
        Categorical.isna : Boolean inverse of Categorical.notna.

        )r'   r   s    rv   notnazCategorical.notna  s    $ 		|rx   c                   ddl m}m} | j                  | j                  }}t        |      |dk\  }}t        j                  |      |j                         }	}|s|	r%|	r|n||   }
t        j                  |
|xs d      }n@t        j                  t        j                  |||            }t        j                  |d      }t        || j                  j                        }| j                  |      } || ||      ddd      S )	a{  
        Return a Series containing counts of each category.

        Every category will have an entry, even those with a count of 0.

        Parameters
        ----------
        dropna : bool, default True
            Don't include counts of NaN.

        Returns
        -------
        counts : Series

        See Also
        --------
        Series.value_counts
        r   )CategoricalIndexrJ   )	minlengthrT   rG  countF)indexrg   namerS   )r   rh  rJ   rb   r^   rW   ri   aranger   bincountr   appendr   rg   _from_backing_data)rk   r*  rh  rJ   coder   ncatrq   ixcleanobsrj  s               rv   value_countszCategorical.value_counts  s    &	

 KKc#h	dIIdOTXXZEU$T$ZCKKtyq9EKKtT :;E2r"B!"djj&;&;<$$R()"-W7QV
 	
rx   c                    | j                  g |      }t        j                  ||j                  j                        }|j                  |      S )z
        Analogous to np.empty(shape, dtype=dtype)

        Parameters
        ----------
        shape : tuple[int]
        dtype : CategoricalDtype
        r   )r   ri   zerosr   rg   rp  )r   r   rg   r   backings        rv   _emptyzCategorical._empty>  sF       5 1
 ((5(:(:;%%g..rx   c                   t        | j                  j                        r5| j                  j                  | j                  t
              j                  S t        | j                  j                        r\d| j                  v rN| j                  j                  d      j                  | j                  t        j                        j                  S t        j                  |       S )a  
        Return the values.

        For internal compatibility with pandas formatting.

        Returns
        -------
        np.ndarray or ExtensionArray
            A numpy array or ExtensionArray of the same dtype as
            categorical.categories.dtype.
        r   rT   r   )r   r^   rg   r1  rb   r   r   r   r   ri   r9  rj   r   s    rv   _internal_get_valuesz Categorical._internal_get_valuesS  s     t445??'''DLLLdoo334t{{9J&&x0dkkbff5
 xx~rx   c                :    | j                   st        d| d      y)zassert that we are orderedz)Categorical is not ordered for operation zG
you can use .as_ordered() to change the Categorical to an ordered one
N)rY   rZ   )rk   rt   s     rv   check_for_orderedzCategorical.check_for_orderedj  s-    ||;B4 @2 2  rx   	quicksort	ascendingr   c               (    t        |   d||d|S )a  
        Return the indices that would sort the Categorical.

        Missing values are sorted at the end.

        Parameters
        ----------
        ascending : bool, default True
            Whether the indices should result in an ascending
            or descending sort.
        kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
            Sorting algorithm.
        **kwargs:
            passed through to :func:`numpy.argsort`.

        Returns
        -------
        np.ndarray[np.intp]

        See Also
        --------
        numpy.ndarray.argsort

        Notes
        -----
        While an ordering is applied to the category values, arg-sorting
        in this context refers more to organizing and grouping together
        based on matching category values. Thus, this function can be
        called on an unordered Categorical instance unlike the functions
        'Categorical.min' and 'Categorical.max'.

        Examples
        --------
        >>> pd.Categorical(['b', 'b', 'a', 'c']).argsort()
        array([2, 0, 1, 3])

        >>> cat = pd.Categorical(['b', 'b', 'a', 'c'],
        ...                      categories=['c', 'b', 'a'],
        ...                      ordered=True)
        >>> cat.argsort()
        array([3, 0, 1, 2])

        Missing values are placed at the end

        >>> cat = pd.Categorical([2, None, 1])
        >>> cat.argsort()
        array([2, 0, 1])
        r  r   )r   argsort)rk   r  r   rV  r   s       rv   r  zCategorical.argsorts  s    f wHHHHrx   )inplacer  na_positionc                    y r   r   rk   r  r  r  s       rv   r   zCategorical.sort_values  s     	rx   r  r  c                    y r   r   r  s       rv   r   zCategorical.sort_values  s     	rx   lastc                   t        |d      }|dvrt        dt        |             t        | ||      }|s | j                  |   }| j                  |      S | j                  |   | j                  dd y)a  
        Sort the Categorical by category value returning a new
        Categorical by default.

        While an ordering is applied to the category values, sorting in this
        context refers more to organizing and grouping together based on
        matching category values. Thus, this function can be called on an
        unordered Categorical instance unlike the functions 'Categorical.min'
        and 'Categorical.max'.

        Parameters
        ----------
        inplace : bool, default False
            Do operation in place.
        ascending : bool, default True
            Order ascending. Passing False orders descending. The
            ordering parameter provides the method by which the
            category values are organized.
        na_position : {'first', 'last'} (optional, default='last')
            'first' puts NaNs at the beginning
            'last' puts NaNs at the end

        Returns
        -------
        Categorical or None

        See Also
        --------
        Categorical.sort
        Series.sort_values

        Examples
        --------
        >>> c = pd.Categorical([1, 2, 2, 1, 5])
        >>> c
        [1, 2, 2, 1, 5]
        Categories (3, int64): [1, 2, 5]
        >>> c.sort_values()
        [1, 1, 2, 2, 5]
        Categories (3, int64): [1, 2, 5]
        >>> c.sort_values(ascending=False)
        [5, 2, 2, 1, 1]
        Categories (3, int64): [1, 2, 5]

        >>> c = pd.Categorical([1, 2, 2, 1, 5])

        'sort_values' behaviour with NaNs. Note that 'na_position'
        is independent of the 'ascending' parameter:

        >>> c = pd.Categorical([np.nan, 2, 2, np.nan, 5])
        >>> c
        [NaN, 2, 2, NaN, 5]
        Categories (2, int64): [2, 5]
        >>> c.sort_values()
        [2, 2, 5, NaN, NaN]
        Categories (2, int64): [2, 5]
        >>> c.sort_values(ascending=False)
        [5, 2, 2, NaN, NaN]
        Categories (2, int64): [2, 5]
        >>> c.sort_values(na_position='first')
        [NaN, NaN, 2, 2, 5]
        Categories (2, int64): [2, 5]
        >>> c.sort_values(ascending=False, na_position='first')
        [NaN, NaN, 5, 2, 2]
        Categories (2, int64): [2, 5]
        r  )r  firstzinvalid na_position: r  N)r   rX   reprr7   rb   rp  )rk   r  r  r  
sorted_idxra   s         rv   r   zCategorical.sort_values  s|    R &gy9//4T+5F4GHIIdi[Q
KK
+E**511Z0Arx   r   averagekeepaxisrT  	na_optionr  pctc               n    |dk7  rt         | j                         }t        j                  ||||||      S )z*
        See Series.rank.__doc__.
        r   r  )r   _values_for_rankr(   rank)rk   r  rT  r  r  r  vffs          rv   _rankzCategorical._rank  sB     19%%##%
 	
rx   c                   ddl m} | j                  rG| j                  }|dk(  }|j	                         r$|j                  d      }t        j                  ||<   |S t        | j                  j                        rt        j                  |       }|S t        j                  | j                   || j                  d      j                         j                              }|S )z
        For correctly ranking ordered categorical data. See GH#15420

        Ordered categorical data should be ranked on the basis of
        codes with -1 translated to NaN.

        Returns
        -------
        numpy.array

        r   r"  rT   float64FrR   )r   rJ   rY   ra   rc   r   ri   r9  r   r^   rg   rj   r  r  r   )rk   rJ   r   rq   s       rv   r  zCategorical._values_for_rank%  s     	"<<ZZFR<Dxxzy1!vvt  't'<'<=XXd^F  XX&&4??7<<>EEF
 rx   c               p   ddl m} t        j                  | j                  j
                        } ||||d      }| j                         }t        |      r|j                  | j                        }n t        j                  t        |      d      }|j                         rt        j                  ||<   |S )aA  
        Hash a Categorical by hashing its categories, and then mapping the codes
        to the hashes.

        Parameters
        ----------
        encoding : str
        hash_key : str
        categorize : bool
            Ignored for Categorical.

        Returns
        -------
        np.ndarray[uint64]
        r   )
hash_arrayF)
categorizeuint64r   )pandas.core.util.hashingr  ri   r   r^   r   r'   rW   r1  rb   rx  rc   r   u8max)	rk   encodinghash_keyr  r  r   hashedrq   r   s	            rv   _hash_pandas_objectzCategorical._hash_pandas_objectE  s    & 	8 DOO334FHh5I yy{v;[[-FXXc$ix8F88:99F4Lrx   c                    | j                   S r   )r   r   s    rv   rb   zCategorical._codess  s    }}rx   c                J    |dk(  rt         j                  S | j                  |   S r   )ri   r9  r^   )rk   rr   s     rv   	_box_funczCategorical._box_funcw  s!    766Mq!!rx   c                    | j                   j                  |      }| j                  j                  j	                  |      }|S r   )r^   r   r   rg   rf   )rk   r   rq  s      rv   rd   zCategorical._unbox_scalar|  s7     &&s+}}""''-rx   c                      j                   dk(  r't         j                         j                               S  fdt	        t                     D        S )zJ
        Returns an Iterator over the values of this Categorical.
        r   c              3  (   K   | ]	  }|     y wr   r   )r   nrk   s     rv   r   z'Categorical.__iter__.<locals>.<genexpr>  s     6%5DG%5s   )r   iterr|  r   rangerW   r   s   `rv   __iter__zCategorical.__iter__  sA     99>113::<==6U3t9%566rx   c                    t        || j                  j                        r't        | j	                         j                               S t        | || j                        S )z?
        Returns True if `key` is in this Categorical.
        )r   )r&   r^   rg   boolr'   rc   r   rb   )rk   r   s     rv   __contains__zCategorical.__contains__  sC    
 !doo&;&;<		)**cT[[99rx   c                     y r   r   )rk   boxeds     rv   
_formatterzCategorical._formatter  s    rx   c                f   t        d      dk(  rdn
t        d      }ddlm} d}| j                  j                  dk(  r4t        t        | j                  j                        j                  d      }t        |j                  |t        	      }t        | j                        |kD  rN|d
z  } || j                  d| j                        } || j                  | d j                        }|dgz   |z   }n || j                  j                        }|D 	cg c]  }	|	j                          }}	|S c c}	w )z9
        return the base repr for the categories
        zdisplay.max_categoriesr   
   formatNstrF)r  )	formatterquoting   z...)r   pandas.io.formatsr  r^   rg   r	   r1   r   r  r   format_arrayr   rW   strip)
rk   max_categoriesfmtr  r  numheadtailcategory_strsxs
             rv   _repr_categorieszCategorical._repr_categories  s'    23q8 45 	
 	4	??  E) ^T__-D-DEPP Q I 	;K
 t.0 A%C 5 = =>D 6 > >?D E7NT1M()@)@AM -::MqM: ;s   D.c                Z   | j                         }t        | j                  j                        }dt	        | j                         d| d}t               \  }}t        d      xs |}t        j                         rd}d}d}t	        |      }	| j                  rdnd	\  }
}|j                          d
}|D ]]  }|dk7  r:|	|
z   t	        |      z   |kD  r&||dt	        |      dz   z  z   z  }t	        |      dz   }	n|s||z  }|	t	        |      z  }	||z  }d}_ | d|j                  dd       dS )z@
        Returns a string representation of the footer.
        zCategories (, z): zdisplay.widthr    T)   z < )r  r  
 r   F[z	 < ... < z ... ])r  r  r^   rg   rW   r   r   r9   in_ipython_frontendrY   rstripreplace)rk   r  rg   	levheaderwidth_	max_width	levstringstartcur_col_lensep_lenseplinesepvals                 rv   _get_repr_footerzCategorical._get_repr_footer  sD    --/DOO))*"3t#7"85'E	$&q/85	&&(I	)n%)\\zyZZ\N"% CA~+"7#c("BY"NWs9~/A(BCC	!)nq0S 	s3x'IE ! Ai//WEFaHHrx   c                    ddl m} t        |       dkD  sJ | j                         }|j	                  |d d dt
              }|D cg c]  }|j                          }}dj                  |      }d|z   dz   }|S c c}w )Nr   r  NaN)float_formatna_repr  r  r  r  )r  r  rW   r|  r  r   r  join)rk   r  vals
fmt_valuesrr   joinedr   s          rv   _get_values_reprzCategorical._get_values_repr  s    34y1}}((*%%$ & 

 *44Aaggi
4:&v# 5s   A9c                D   | j                         }t        |       }d}||kD  rV|dz  }| d| j                         }| ||z
   d j                         }|dd  d|dd  }dt        |        }| d| d| }	|	S |d	kD  r| j                         }| d| }	|	S d
}| d| }	|	S )z(
        String representation.
        r  r  NrT   z, ..., r   zLength: r  r   z[]r  )r  rW   r  )
rk   footerlengthmax_lenr  r  r  bodylength_infor   s
             rv   __repr__zCategorical.__repr__  s     &&(TG Q,C:..0D'C-(*+<<>D3Bi[QRz2D$SYK0KvR}Bvh7F  aZ((*DvRx(F  DvRx(Frx   c                   t        |d      }t        |t              rA| j                  |j                  k7  rt	        d      | j                  |      }|j                  S ddlm}  |j                  |d      j                  | j                        }t        |      r$t        |      j                         st	        d      | j                  j                  |      }|j!                  | j"                  j                  d	      S )
NT)extract_numpyzCCannot set a Categorical with another, without identical categoriesr   r(  F)tupleize_colszMCannot setitem on a Categorical with a new category, set the categories firstrR   )r4   r[   r\   rg   rZ   _encode_with_my_categoriesrb   r   rI   _with_inferr  r^   rW   r'   r   get_indexerr   r   )rk   r  rI   to_addra   s        rv   rB  zCategorical._validate_listlike	  s    e48 e[)zzU[[(3 
 33E:E<<  #""5>IIOO
 v;tF|//15 
 ++E2||DMM//e|<<rx   c                   | j                   }t        j                  t        | j                        |j
                        \  }t        |      j                         }fdt        ||dd       D        }t        t        ||            S )a  
        Compute the inverse of a categorical, returning
        a dict of categories -> indexers.

        *This is an internal function*

        Returns
        -------
        Dict[Hashable, np.ndarray[np.intp]]
            dict of categories -> indexers

        Examples
        --------
        >>> c = pd.Categorical(list('aabca'))
        >>> c
        ['a', 'a', 'b', 'c', 'a']
        Categories (3, object): ['a', 'b', 'c']
        >>> c.categories
        Index(['a', 'b', 'c'], dtype='object')
        >>> c.codes
        array([0, 0, 1, 2, 0], dtype=int8)
        >>> c._reverse_indexer()
        {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}

        c              3  .   K   | ]  \  }}||   y wr   r   )r   r  endrs      rv   r   z/Categorical._reverse_indexer.<locals>.<genexpr>N	  s     J2IJE31U3<2Is   r   N)
r^   libalgosgroupsort_indexerr   ra   r0  r   cumsumzipr[  )rk   r^   counts_resultr  s       @rv   _reverse_indexerzCategorical._reverse_indexer/	  sr    4 __
..

+Z__
	6 f%,,.J#ffQRj2IJC
G,--rx   skipnakeepdimsc               x    t        |   |f||d|}|dv r|S |r t        |       || j                        S |S )Nr  )argmaxargminr   )r   _reducerf   rg   )rk   rl  r  r  rV  r   r   s         rv   r  zCategorical._reduceT	  sL     RfxR6R''M4:fDJJ77Mrx   )r  c                  t        j                  |j                  dd             t        j                  d|       | j	                  d       t        | j                        s| j                  j                  S | j                  dk7  }|j                         s@|r.|j                         r| j                  |   j                         }n*t        j                  S | j                  j                         }| j                  d|      S )a/  
        The minimum value of the object.

        Only ordered `Categoricals` have a minimum!

        Raises
        ------
        TypeError
            If the `Categorical` is not `ordered`.

        Returns
        -------
        min : the minimum of this `Categorical`, NA value if empty
        r  r   r   rI  rT   N)nvvalidate_minmax_axisr  validate_minr~  rW   rb   rg   na_valuer   rc   rI  ri   r9  _wrap_reduction_resultrk   r  rV  goodpointers        rv   rI  zCategorical.min`	       	

61 56
F#u%4;;::&&&{{b xxz$((*++d+//1vvkkoo'G**499rx   c                  t        j                  |j                  dd             t        j                  d|       | j	                  d       t        | j                        s| j                  j                  S | j                  dk7  }|j                         s@|r.|j                         r| j                  |   j                         }n*t        j                  S | j                  j                         }| j                  d|      S )a2  
        The maximum value of the object.

        Only ordered `Categoricals` have a maximum!

        Raises
        ------
        TypeError
            If the `Categorical` is not `ordered`.

        Returns
        -------
        max : the maximum of this `Categorical`, NA if array is empty
        r  r   r   rH  rT   N)r
  r  r  validate_maxr~  rW   rb   rg   r  r   rc   rH  ri   r9  r  r  s        rv   rH  zCategorical.max	  r  rx   c                    | j                   }d }|r| j                         }t        j                  ||      }t	        t
        j                  |      }|j                  |j                  k(  sJ | j                  |      }|S )N)rq   )	rb   r'   r(   moder	   ri   r   rg   rp  )rk   r*  ra   rq   	res_codesr   s         rv   _modezCategorical._mode	  si    99;DOOE5	Y/	%++---%%i0
rx   c                     t         |          S )a  
        Return the ``Categorical`` which ``categories`` and ``codes`` are
        unique.

        .. versionchanged:: 1.3.0

            Previously, unused categories were dropped from the new categories.

        Returns
        -------
        Categorical

        See Also
        --------
        pandas.unique
        CategoricalIndex.unique
        Series.unique : Return unique values of Series object.

        Examples
        --------
        >>> pd.Categorical(list("baabc")).unique()
        ['b', 'a', 'c']
        Categories (3, object): ['a', 'b', 'c']
        >>> pd.Categorical(list("baab"), categories=list("abc"), ordered=True).unique()
        ['b', 'a']
        Categories (3, object): ['a' < 'b' < 'c']
        )r   r)  )rk   r   s    rv   r)  zCategorical.unique	  s    : w~rx   r   c                    t        |t              sy| j                  |      r;| j                  |      }t	        j
                  | j                  |j                        S y)z
        Returns True if categorical arrays are equal.

        Parameters
        ----------
        other : `Categorical`

        Returns
        -------
        bool
        F)r[   r\   r]   r  ri   array_equalrb   rk   rl   s     rv   r_   zCategorical.equals	  sK     %-55e<33E:E>>$++u||<<rx   c           	        ddl m} |d   }||j                  k\  rt        d| d|j                         |dk(  rt	        d |D              st        g }|D ]>  }|j                  t        |j                  d         D cg c]  }|d d |f    c}       @ | j                  |d      }|j                  t        |      dd	
      }	|	S  ||      }	|	S c c}w )Nr   )union_categoricalszaxis z) is out of bounds for array of dimension r   c              3  :   K   | ]  }|j                   d k(    yw)r  N)r   )r   r  s     rv   r   z0Categorical._concat_same_type.<locals>.<genexpr>	  s     6Iqqvv{Is   r  rT   F)order)pandas.core.dtypes.concatr  r   rX   r   extendr  r   _concat_same_typereshaperW   )
r   	to_concatr  r  r  tc_flatobjrr   res_flatr   s
             rv   r%  zCategorical._concat_same_type	  s    @!5::vFuzzlS  196I66   G 513FG3FaAqD	3FGH ! ,,W1,=H%%c%j"C%@FM#I.  Hs   ?C
c                ~    t        |j                  |j                  | j                  d      }| j                  |      S )z
        Re-encode another categorical using this Categorical's categories.

        Notes
        -----
        This assumes we have already checked
        self._categories_match_up_to_permutation(other).
        FrR   )r`   ra   r^   rp  )rk   rl   ra   s      rv   r  z&Categorical._encode_with_my_categories	  s8     &KK))4??
 &&u--rx   c                X    t        | j                        t        |j                        k(  S )z
        Returns True if categoricals are the same dtype
          same categories, and same ordered

        Parameters
        ----------
        other : Categorical

        Returns
        -------
        bool
        )r   rg   r  s     rv   r]   z/Categorical._categories_match_up_to_permutation
  s!     DJJ4#444rx   c                    | j                  d      }||j                         z  }ddlm} ddlm}  |||gd      } |dd	g      |_        d
|j                  _        |S )z
        Describes this Categorical

        Returns
        -------
        description: `DataFrame`
            A dataframe with frequency and counts by category.
        F)r*  r   r(  )concatr   r   r  freqsr^   )	rv  sumr   rI   pandas.core.reshape.concatr.  columnsrk  rl  )rk   r  r/  rI   r.  r   s         rv   describezCategorical.describe
  s_     ""%"0% 5a0'23(rx   c                    t        j                  t        |            }| j                  j	                  |      }|||dk\  z     }t        j                  | j                  |      S )a  
        Check whether `values` are contained in Categorical.

        Return a boolean NumPy Array showing whether each element in
        the Categorical matches an element in the passed sequence of
        `values` exactly.

        Parameters
        ----------
        values : np.ndarray or ExtensionArray
            The sequence of values to test. Passing in a single string will
            raise a ``TypeError``. Instead, turn a single string into a
            list of one element.

        Returns
        -------
        np.ndarray[bool]

        Raises
        ------
        TypeError
          * If `values` is not a set or list-like

        See Also
        --------
        pandas.Series.isin : Equivalent method on Series.

        Examples
        --------
        >>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',
        ...                'hippo'])
        >>> s.isin(['cow', 'lama'])
        array([ True,  True,  True, False,  True, False])

        Passing a single string as ``s.isin('lama')`` will raise an error. Use
        a list of one element instead:

        >>> s.isin(['lama'])
        array([ True, False,  True, False,  True, False])
        r   )ri   r   r'   r^   get_indexer_forr(   r   ra   )rk   r   r   code_valuess       rv   r   zCategorical.isin4
  sT    R JJtF|,	oo55f=!){a/?"@Atzz;77rx   )r  c               >   ddl m} | j                  }t        |d      }|r| n| j	                         }t        t        j                  |            }|j                         r|t        j                  |      |   }|j                  |j                  j                  |         }|j                  |      }	t        j                  ||	j                  |	j                         |j                  j                         }
|
j!                  ||      }
 ||
      }|j                  j#                  |      }t        j$                  t'        |
            }t        j(                  |dk(  ||      }|j+                         }|
j-                  |      }|j/                  d      } ||      }t1        |j2                  ||d	      }t5        || j                  j6                  
      }t        j                  |||       ||k7  r$t9        j:                  dt<        t?                      |s|S y )Nr   r(  r  )
to_replacer  rT   r  )r  FrR   r   zThe behavior of Series.replace (and DataFrame.replace) with CategoricalDtype is deprecated. In a future version, replace will only be used for cases that preserve the categories. To change the categories, use ser.cat.rename_categories instead.r   ) r   rI   rg   r   rS   r'   ri   r   rc   r^   r   r-  r   r   ra   	to_seriesr  r5  rm  rW   r   r  r1  drop_duplicatesr`   rb   r!   rY   r   r   r   r   )rk   r8  r  r  rI   
orig_dtyper   rq   r+  new_catser
all_valuesidxrlocsr  r3  r	  s                    rv   _replacezCategorical._replaceb
  s    ZZ
%gy9d499;BJJu%&88:zz*-d3H~~cnn&9&9(&CDH++H5G""3w}}Enn&&(kkZuk=3Z
 ~~--j9yyS"xx
D$/||~$'77W7E~.)JJ
N
	 %^TZZ=O=OP	sIy9
"MM
 +-	 J rx   c                   | j                   }| j                  }|j                  dk(  rn|j                  j	                  |||      }|j                  j
                  t        j                  u rXt        |      rM|t        j                  u st        |      r0d}n-ddlm}  ||j                               j	                  |||      }t        |||      S )NstringFr   NumpyExtensionArrayr   )r^   ra   rg   rj   _str_mapr  ri   r9  r   r   r   r'   pandas.core.arraysrE  r   r.   )	rk   fr  rg   convertr^   ra   r   rE  s	            rv   rF  zCategorical._str_map
  s     __


x'%%..q(EBF  ))RVV3!%(/4> !>()<)<)>?HH8UF vu::rx   c                f    ddl m}  || j                  t        d            j	                  |      S )Nr   rD  r  )r  )rG  rE  r   r  _str_get_dummies)rk   r  rE  s      rv   rK  zCategorical._str_get_dummies
  s-    :"4==u=#EFWW
 	
rx   c          	        ddl m} |j                  |      } ||||      }	| j                  }
|dv rt	        |
 d| d      |dv r|
j
                  st	        d| d	      |d
vr'|dk(  rt	        |
 d| d      t	        |
 d| d      d }| j                         }|dk(  r| j
                  sJ | j                  }nA|dv r(| j                  }t        j                  |t              }n| j                  t              } |	j                  |f|||||d|}||	j                  v r|S |dv rd||dk(  <   | j                  |      S )Nr   )WrappedCythonOp)howr   has_dropped_na)r0  prodr  cumprodskewz type does not support z operations)rI  rH  r  idxminidxmaxzCannot perform z with non-ordered Categorical)	r  rc   r   r  r  rI  rH  rS  rT  	transformz% dtype does not support aggregation ''r  )r  r  rI  rH  rS  rT  r   )	min_countngroupscomp_idsrq   result_mask)r  r  rI  rH  rT   r   )pandas.core.groupby.opsrM  get_kind_from_howrg   rZ   rY   r'   r   ri   rx  r  r   _cython_op_ndim_compatcast_blocklistrp  )rk   rN  rO  rW  rX  idsrV  rM  r   rt   rg   rZ  rq   npvalues
res_valuess                  rv   _groupby_opzCategorical._groupby_op
  s    	<0054O

>>ug%<SEMNN<<U]] ocU2OPQQ 

 

 {"5')@[ QRRug%J3%qQRRyy{&=<<<}}HGG}}H((7$7K {{4(H.R..
#
 

 "###33+-J{a'(&&z22rx   )ra   
np.ndarrayrg   r!   returnrD   )rg   Dtype | Noner   zbool | lib.NoDefaultrS   r  rd  None)rd  r!   )rd  int)rg   re  rS   r  rd  rD   )rg   rA   rd  rD   ).)rg   znpt.DTypeLikerS   r  rd  rc  )rg   r#   rS   r  rd  r1   )rg   r>   rS   r  rd  r=   Tr   )rd  rD   )NNNT)rg   re  r   r  rd  rD   )rd  rI   )rd  rC   )rd  rc  )F)r   r  rd  rf  )rg   r!   rd  rD   )r  r  rd  rD   )NF)r  r  )r>  z(Literal['ignore'] | None | lib.NoDefault)rg   r!   rd  rc  )NN)rg   zNpDtype | NonerS   zbool | Nonerd  rc  )rS  znp.ufuncrT  r  rd  rf  )rb  r  rd  rg  )rd  npt.NDArray[np.bool_])r*  r  rd  rJ   )r   rE   rg   r!   rd  rD   )rd  r=   )r  r  r   rF   )r  zLiteral[False]r  r  r  r  rd  rD   )r  zLiteral[True]r  r  r  r  rd  rf  )r  r  r  r  r  r  rd  zSelf | None)
r  r?   rT  r  r  r  r  r  r  r  )r  r  r  r  r  r  rd  znpt.NDArray[np.uint64])rr   rg  )rd  r;   rd  r  )r  r  )rd  z	list[str])rd  r  )rd  z$dict[Hashable, npt.NDArray[np.intp]])rl  r  r  r  r  r  )r  r  )r*  r  rd  r\   )rl   r   rd  r  )r   )r'  zSequence[Self]r  r?   rd  rD   )rl   r\   rd  r\   )rl   r\   rd  r  )rd  rH   )r   r=   rd  rj  )r  r  )rI  r  )|)r  r  )
rN  r  rO  r  rW  rg  rX  rg  r_  znpt.NDArray[np.intp])iry   
__module____qualname____doc____array_priority__r3   _hidden_attrs	frozenset_typ__annotations__classmethodr   r   r   r   propertyrg   r   r   r   r
   r   r   r   r   r^   rY   ra   r
  r   r  r  r  r  r  r   r&  r-  r4  r8  r|   rz   eqrU   r{   rV   ltrN   gtrO   lerP   gerQ   rD  rC  r   r0   rK  rW  r\  r`  rc  r'   isnullrf  notnullrv  rz  r|  r~  r  r   r  r  r  rb   r  rd   r  r  r  r  r  r  r  rB  r  r  rI  rH  r  r)  r_   r%  r  r]   r3  r   rA  ri   rF  rK  rb  __classcell__)r   s   @rv   r\   r\      s	   eR  ..H:1FFMD11'71	1	 1 "),y%
 y% 'y% y% 
y%v     /3%4 ,4;?4	4 4
        :x EIB3	B3 B3H  "B3
 B3 B3 
B3 B3N 7% 7%r %" %"N # #J#3J: &>'@hTFPIDVCJ:Wx/l ?Bnnm4 <m4^ X[[)FX[[)FX[[)FX[[)FX[[)FX[[)F
0:  " @D4,#4,2=4,	4, 4,l
:$ H HR2!& F( G(
Z //"2/	/ /(. $(+3I 3I/73Ij  #&   	
  
  ;>SV'48MP	  !S S 	S
 S 
Sp 
 
 	

 
 
 
0@))*-);?)	)\  "
7: DI:&:=B .L ,0%

$(
;?
 %) :@ %) :@
 >&  :."5*,8\ >C /h ..0BTX;MQ;2
@3 @3 	@3
 @3 @3 "@3rx   r\   r^   rY   rv  )delegate	accessorstyp)r  r   r&  r-  r4  r  r  r  rT  c                  R    e Zd ZdZd	dZed        Zd
dZd
dZe	dd       Z
d
dZy)CategoricalAccessoraP  
    Accessor object for categorical properties of the Series values.

    Parameters
    ----------
    data : Series or CategoricalIndex

    Examples
    --------
    >>> s = pd.Series(list("abbccc")).astype("category")
    >>> s
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (3, object): ['a', 'b', 'c']

    >>> s.cat.categories
    Index(['a', 'b', 'c'], dtype='object')

    >>> s.cat.rename_categories(list("cba"))
    0    c
    1    b
    2    b
    3    a
    4    a
    5    a
    dtype: category
    Categories (3, object): ['c', 'b', 'a']

    >>> s.cat.reorder_categories(list("cba"))
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (3, object): ['c', 'b', 'a']

    >>> s.cat.add_categories(["d", "e"])
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (5, object): ['a', 'b', 'c', 'd', 'e']

    >>> s.cat.remove_categories(["a", "c"])
    0    NaN
    1      b
    2      b
    3    NaN
    4    NaN
    5    NaN
    dtype: category
    Categories (1, object): ['b']

    >>> s1 = s.cat.add_categories(["d", "e"])
    >>> s1.cat.remove_unused_categories()
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (3, object): ['a', 'b', 'c']

    >>> s.cat.set_categories(list("abcde"))
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (5, object): ['a', 'b', 'c', 'd', 'e']

    >>> s.cat.as_ordered()
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (3, object): ['a' < 'b' < 'c']

    >>> s.cat.as_unordered()
    0    a
    1    b
    2    b
    3    c
    4    c
    5    c
    dtype: category
    Categories (3, object): ['a', 'b', 'c']
    c                    | j                  |       |j                  | _        |j                  | _        |j
                  | _        | j                          y r   )	_validater   _parentrk  _indexrl  _name_freeze)rk   datas     rv   r   zCategoricalAccessor.__init__z  s8    t{{jjYY
rx   c                N    t        | j                  t              st        d      y )Nz2Can only use .cat accessor with a 'category' dtype)r[   rg   r!   AttributeError)r  s    rv   r  zCategoricalAccessor._validate  s"    $**&67 !UVV 8rx   c                .    t        | j                  |      S r   )rh   r  )rk   rl  s     rv   _delegate_property_getz*CategoricalAccessor._delegate_property_get  s    t||T**rx   c                0    t        | j                  ||      S r   )setattrr  )rk   rl  
new_valuess      rv   _delegate_property_setz*CategoricalAccessor._delegate_property_set  s    t||T:66rx   c                ^    ddl m}  || j                  j                  | j                        S )a@  
        Return Series of codes as well as the index.

        Examples
        --------
        >>> raw_cate = pd.Categorical(["a", "b", "c", "a"], categories=["a", "b"])
        >>> ser = pd.Series(raw_cate)
        >>> ser.cat.codes
        0   0
        1   1
        2  -1
        3   0
        dtype: int8
        r   r"  )rk  )r   rJ   r  ra   r  )rk   rJ   s     rv   ra   zCategoricalAccessor.codes  s"      	"dll((<<rx   c                    ddl m} t        | j                  |      } ||i |}| ||| j                  | j
                        S y )Nr   r"  )rk  rl  )r   rJ   rh   r  r  r  )rk   rl  argsrV  rJ   rT  r   s          rv   _delegate_methodz$CategoricalAccessor._delegate_method  sE    !t,d%f%?#T[[tzzBB rx   Nri  )rl  r  )rd  rJ   )ry   rm  rn  ro  r   staticmethodr  r  r  rv  ra   r  r   rx   rv   r  r  
  sH    $gR W W+
7 = =&Crx   r  c                <    |j                  |       }t        ||      S )z
    utility routine to turn values into codes given the specified categories

    If `values` is known to be a Categorical, use recode_for_categories instead.
    )r5  r   )r   r^   ra   s      rv   r   r     s!     &&v.Ez22rx   c                    t        |      dk(  r|r| j                         S | S |j                  |      r|r| j                         S | S t        |j	                  |      |      }t        || d      }|S )a#  
    Convert a set of codes for to a new set of categories

    Parameters
    ----------
    codes : np.ndarray
    old_categories, new_categories : Index
    copy: bool, default True
        Whether to copy if the codes are unchanged.

    Returns
    -------
    new_codes : np.ndarray[np.int64]

    Examples
    --------
    >>> old_cat = pd.Index(['b', 'a', 'c'])
    >>> new_cat = pd.Index(['a', 'b'])
    >>> codes = np.array([0, 1, 1, 2])
    >>> recode_for_categories(codes, old_cat, new_cat)
    array([ 1,  0,  0, -1], dtype=int8)
    r   rT   r   )rW   rS   r_   r   r5  r.   )ra   old_categoriesr  rS   indexerr3  s         rv   r`   r`     sw    2 >a::<			~	.::<"&&~6G 26Irx   c                   ddl m} t        |       st        d      t	        | dd      }t        |t              rt        |       } t        j                  t        | j                        | j                  j                        }t        j                  || j                  d      } ||      }| j                  }||fS t        | d	      }|j                  }|j                  }||fS )
az  
    Factorize an input `values` into `categories` and `codes`. Preserves
    categorical dtype in `categories`.

    Parameters
    ----------
    values : list-like

    Returns
    -------
    codes : ndarray
    categories : Index
        If `values` has a categorical dtype, then `categories` is
        a CategoricalIndex keeping the categories and order of `values`.
    r   )rh  zInput must be list-likerg   Nr   Fr7  r   )r   rh  r   rZ   rh   r[   r!   r4   ri   rm  rW   r^   ra   rg   r\   r   )r   rh  r   	cat_codesr   r^   ra   s          rv   factorize_from_iterabler    s      (122 VWd+F&*+v& IIc&"3"34FLL<N<NO	$$YfllU$S%c*
 * &%0^^
		*rx   c                v    t        |       dk(  rg g fS t        d | D         \  }}t        |      t        |      fS )a$  
    A higher-level wrapper over `factorize_from_iterable`.

    Parameters
    ----------
    iterables : list-like of list-likes

    Returns
    -------
    codes : list of ndarrays
    categories : list of Indexes

    Notes
    -----
    See `factorize_from_iterable` for more info.
    r   c              3  2   K   | ]  }t        |        y wr   )r  )r   its     rv   r   z+factorize_from_iterables.<locals>.<genexpr>&  s     NIb5b9Is   )rW   r  r   )	iterablesra   r^   s      rv   factorize_from_iterablesr    sB    " 9~2vNINOE:;Z(((rx   rk  )r   z,Index | Series | ExtensionArray | np.ndarrayr^   rI   rd  rc  rh  )ra   rc  rS   r  rd  rc  )rd  ztuple[np.ndarray, Index])rd  z$tuple[list[np.ndarray], list[Index]])w
__future__r   csvr   	functoolsr   rz   shutilr   typingr   r   r	   r
   r   numpyri   pandas._configr   pandas._libsr   r   r  r   pandas._libs.arraysr   pandas.compat.numpyr   r
  pandas.util._exceptionsr   pandas.util._validatorsr   pandas.core.dtypes.castr   r   pandas.core.dtypes.commonr   r   r   r   r   r   r   r   r   r   r   pandas.core.dtypes.dtypesr    r!   r"   r#   pandas.core.dtypes.genericr$   r%   pandas.core.dtypes.missingr&   r'   pandas.corer(   r)   r*   pandas.core.accessorr+   r,   pandas.core.algorithmsr-   r.   pandas.core.arrays._mixinsr/   r0   pandas.core.baser1   r2   r3   pandas.core.commoncorecommonr   pandas.core.constructionr4   r5   pandas.core.ops.commonr6   pandas.core.sortingr7    pandas.core.strings.object_arrayr8   r  r9   collections.abcr:   r;   r<   pandas._typingr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   r   rH   rI   rJ   r|   r   r\   r  r   r`   r  r  r   rx   rv   <module>r     s   "     $    % 
 . . 4 7    
 
 
 !   < ( C %     FR06fC(3-|=S C(3RP \9$=: 	 	XC.,8L XC"XC|
38
3
3 
3 EI((=A((V(V)rx   