o
    5ct                    @  s  U d dl mZ d dlmZ d dlZd dlmZ d dl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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m Z  d dl!m"  m#Z$ d dl%m&Z&m'Z' d d	l(m)Z) d d
l*m+Z+m,Z,m-Z-m.Z.m/Z/ d dl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 d dl:m;Z< d dl=m>Z>m?Z?m@Z@ d dlAmBZBmCZCmDZDmEZE d dlFmGZGmHZH d dlImJZJ d dlKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZS d dlTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZl d dlmmnZn d dlompZpmqZqmrZrmsZsmtZtmuZu d dlvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z} d dl~mZ d dlmZmZmZ d dlmZmZmZ d dlmZ d dlm  mZ d dlmZmZ d dlmZmZ d dlmZmZ d dlmZ d dlmZ d dlmZmZ d dlm  mZ d d lmZmZmZ d d!lmZ d d"lmZ d d#lmZ d d$lmZ d d%lmZmZmZ d d&lmZ d d'lmZmZmZmZ erd d(lmZmZmZmZ d d)lmZ d*gZed+Zd*d,d*d,d*d-d.Zd/ed0< i Zd/ed1< eZed2Zdhd6d7Zdid;d<Zd=d> Zed?d*d@ZG dAd* d*eeZdjdkdBdCZdldmdIdJZdKdL ZdndOdPZdodSdTZdpdVdWZdXZ	Ydqdrd]d^ZdsdadbZdtdddeZdfdg ZdS )u    )annotations)datetimeN)zip_longest)TYPE_CHECKINGAnyCallableClassVarHashableIterableLiteralNoReturnSequenceTypeVarcastfinaloverload)
get_option)NaTalgosindexlib)is_datetime_array
no_default)is_float_nan)IncompatibleFrequencyOutOfBoundsDatetime	Timestampis_unitless
tz_compare)		ArrayLikeAxesDtypeDtypeObjFIgnoreRaiseLevelShapenpt)function)DuplicateLabelErrorIntCastingNaNErrorInvalidIndexError)Appendercache_readonlydeprecate_nonkeyword_argumentsdoc)find_stack_levelrewrite_exception)astype_nansafe)LossySetitemErrorcan_hold_elementcommon_dtype_categorical_compatensure_dtype_can_hold_nafind_common_typeinfer_dtype_frommaybe_cast_pointwise_resultnp_can_hold_element)ensure_int64ensure_objectensure_platform_intis_bool_dtypeis_categorical_dtypeis_dtype_equalis_ea_or_datetimelike_dtypeis_extension_array_dtypeis_floatis_float_dtypeis_hashable
is_integeris_interval_dtypeis_iteratoris_list_likeis_numeric_dtypeis_object_dtype	is_scalaris_signed_integer_dtypeis_string_dtypeis_unsigned_integer_dtypeneeds_i8_conversionpandas_dtypevalidate_all_hashable)concat_compat)CategoricalDtypeDatetimeTZDtypeExtensionDtypeIntervalDtypePandasDtypePeriodDtype)ABCDataFrameABCDatetimeIndexABCMultiIndexABCPeriodIndexABCRangeIndex	ABCSeriesABCTimedeltaIndex)is_dict_like)array_equivalentis_valid_na_for_dtypeisna)	arraylikemissingops)CachedAccessor)setitem_datetimelike_compatvalidate_putmask)CategoricalExtensionArray)tz_to_dtypevalidate_tz_from_dtype)SparseDtype)StringArray)IndexOpsMixinPandasObject)ensure_wrapped_if_datetimelikeextract_arraysanitize_array)deprecate_ndim_indexing)
FrozenList)get_op_result_name)make_invalid_op)ensure_key_mappedget_group_index_sorternargsort)StringMethods)
PrettyDictdefault_pprintformat_object_summarypprint_thing)CategoricalIndex	DataFrame
MultiIndexSeries)PeriodArrayIndex)mixedmixed-integer 
np.ndarray)klassinplacetarget_klassraises_sectionunique
duplicatedzdict[str, str]_index_doc_kwargs_index_shared_docsobjectmethr#   returnc                   s,   t  				dd fd	d
}tt|S )zG
    Decorator to simplify 'return_indexers' checks in Index.join.
    leftNFhowstr_treturn_indexersboolsortc           	        sJ    | ||||d\}}}|s|S |d urt |}|d ur t |}|||fS )Nr   levelr   )r=   )	selfotherr   r   r   r   
join_indexlidxridxr    N/var/www/html/gps/gps/lib/python3.10/site-packages/pandas/core/indexes/base.pyjoin   s   	
z$_maybe_return_indexers.<locals>.joinr   NFF)r   r   r   r   r   r   )	functoolswrapsr   r#   )r   r   r   r   r   _maybe_return_indexers   s   
r   kwargsdict[str, Any]Nonec                 C  s   | rt dtt|  d S )NzUnexpected keyword arguments )	TypeErrorreprset)r   r   r   r   disallow_kwargs   s   r   c                 C  s   t | trddlm} || fi |S t | tr,d|v r'd|vr'|d|d< d|d< nd|vr;d|v r;|d j|d< | j| fi |S )	zv
    This is called upon unpickling, rather than the default which doesn't
    have arguments and breaks __new__.
    r   )_new_PeriodIndexlabelscodesFverify_integritydtypedata)
issubclassr]   pandas.core.indexes.periodr   r\   popr   __new__)clsdr   r   r   r   
_new_Index   s   


r   _IndexT)boundc                      s  e Zd ZU dZejejB eddgB Zded< dZ	e
dyddZe
dzddZe
dzddZe
dzddZdZded< ded< ejefZded< dZded< dZded < d!Zd"ed#< d$gZd%ed&< d$gZd%ed'< d!Zd"ed(< d)Zd"ed*< d!Zd"ed+< ed{d-d.Zd!ZdhZe de!Z"	)d|d}d/d0Z#e$d~d2d3Z%e
e$dd6d7Z&	 ed8d9 Z'e$ddd<d=Z(e$d>d? Z)e*dd@dAZ+e
ddCdDZ,e
ddFdGZ-e
ddIdJZ.e/fddKdLZ0ddMdNZ1e
ddOdPZ2e
ddQdRZ3e
ddSdTZ4e
ddUdVZ5e*ddXdYZ6e
e*dd[d\Z7dd^d_Z8dddadbZ9ddgdhZ:ddidjZ;e*ddkdlZ<e
ddndoZ=ddpdqZ>dd~drdsZ?dte@du< eAe@du eB 	dddydzZCe
dd{d|ZDd}e@d~< eAe@d~ eB dddZE		!		ddddZFe
dddZGe
ddddZHe
dddZIdddZJedd ZKddddZLdddZMe
dddZNe
dddZO	!		ddddZPdddZQe
ddddZRddddddZSddddZTdddZUddddZVd)eWj/fdddZXedddZYeYjZdddZYe
	!ddddZ[	ddddZ\dddZ]ddÜdddńZ^ee^e]dƍZ_e`dddgdǍddddʄZaddd̄Zbeddd΄ZcdddЄZde
ddd҄ZedddԄZfdddքZgd}dd؄ZhehZie
dddڄZje
dddބZkdd)dߜdddZle*e
dddZme
edddZnedddZoedddZpe
edddZqe
edddZre*dddZse
edddZte
dddZue
dddZve
dddZwe
dddZxe
dddZye
dddZze
dd dZ{e
dddZ|e
dddZ}e*dddZ~e*e
ddd	Ze*e
dd
dZe
e*dddZdd Ze*dd Ze*dddZe*dddZe
dddZeZe
dddZeZdddZdddd Zdd fd"d#Ze`ddgdǍdd fd'd(Z	$ddd*d+Zd,d- Ze
d.d/ Ze
d0d1 Ze
d2d3 Ze
dd5d6ZeZd7d8 Ze
d9d: Ze
dd<d=Ze
dd>d?Zdd@dAZe
ddBdCZe
ddDdEZdddFdGZdHdI Ze
ddKdLZe
ddMdNZdOdP ZdQdR ZddSdTZe
ddUdVZddXdYZddZd[Zd\e@d]< eAe@d] eB e
			dddadbZ			dddddeZe
ddfdgZe
		dddhdiZddkdlZe
	dddmdnZe
	dddodpZe
ddqdrZe
ddtduZe
dÐdvdwZe
dĐdzd{ZddŐd~dZe
dƐddZe
dǐddZ	dȐdɐddZdʐddZdːddZe
d̐ddZeddddd͐ddZeddddddΐddZeddddddϐddZe
e`ddd	gdǍe			!	!dАdϐddZe
dѐddZe
dҐddZe
	dӐdԐddZe
	)dՐd֐ddZe
	dӐdאddZdؐddZe*dddZedِddZe*eejădڐddZedېddZŐdِddZƐdܐddZeejȃddݐddZe
dd}ddZe
e$dÐdĄ Ze
e$dŐdƄ Z̐dǐdȄ Ze
dɐdʄ Zΐddːd̄Zϐdސd͐d΄ZАdߐdАdфZѐded< e
dԐdՄ ZҐd֐dׄ ZӐddِdڄZe
ddېd܄ZՐddސd߄Z֐dddZe
d}ddZؐdddZe
dddZe
dd ZېdddZ	!	)		ddddZe
dd ZސdddZߐdddZe
dddZdd  Ze*dddZdddZe
dddZde@d< eAe@d eB dd
dZe
dddZdddZdddZe	ddddZedddZe	)ddddZe
	)ddddZedddZdZe
ddd Ze
dd!d"Ze
dd#d$Zdd%d&Ze
dd(d)Zdd*d+Ze
ddÜd}d,d-Zddd.d/Zdd0d1Zddde/fdd5d6Zd7d8 Zd}d9d:Ze
dd;d<Ze/fdd>d?ZdӐddAdBZe/fddCdDZddde/fddFdGZddHdIZddKdLZ	MdddRdSZ dTdU ZdVdW Z fdXdYZe
dZd[ Zd}d\d]Zd}d^d_Zd}d`daZd}dbdcZddde Z	dfdg Z
e
ddidjZeAejjd d fdkdlZeAejjd d fdmdnZeejd  fdodp	Zeejd  fdqdr	Ze
eddtduZe
ddwdxZ  ZS (  r   a  
    Immutable sequence used for indexing and alignment.

    The basic object storing axis labels for all pandas objects.

    Parameters
    ----------
    data : array-like (1-dimensional)
    dtype : NumPy dtype (default: object)
        If dtype is None, we find the dtype that best fits the data.
        If an actual dtype is provided, we coerce to that dtype if it's safe.
        Otherwise, an error will be raised.
    copy : bool
        Make a copy of input ndarray.
    name : object
        Name to be stored in the index.
    tupleize_cols : bool (default: True)
        When True, attempt to create a MultiIndex if possible.

    See Also
    --------
    RangeIndex : Index implementing a monotonic integer range.
    CategoricalIndex : Index of :class:`Categorical` s.
    MultiIndex : A multi-level, or hierarchical Index.
    IntervalIndex : An Index of :class:`Interval` s.
    DatetimeIndex : Index of datetime64 data.
    TimedeltaIndex : Index of timedelta64 data.
    PeriodIndex : Index of Period data.
    NumericIndex : Index of numpy int/uint/float data.
    Int64Index : Index of purely int64 labels (deprecated).
    UInt64Index : Index of purely uint64 labels (deprecated).
    Float64Index : Index of  purely float64 labels (deprecated).

    Notes
    -----
    An Index instance can **only** contain hashable objects

    Examples
    --------
    >>> pd.Index([1, 2, 3])
    Int64Index([1, 2, 3], dtype='int64')

    >>> pd.Index(list('abc'))
    Index(['a', 'b', 'c'], dtype='object')
    contains	set_valuezfrozenset[str]_hidden_attrs   r   r   r   r   npt.NDArray[np.intp]c                 C  s4   |   }|  }ttj|}ttj|}t||S N)_get_engine_targetr   npndarraylibjoinleft_join_indexer_unique)r   r   svovr   r   r   _left_indexer_uniqueT  s
   zIndex._left_indexer_unique<tuple[ArrayLike, npt.NDArray[np.intp], npt.NDArray[np.intp]]c                 C  N   |   }|  }ttj|}ttj|}t||\}}}| |}|||fS r   )r   r   r   r   r   left_join_indexer_from_join_targetr   r   r   r   joined_ndarrayr   r   joinedr   r   r   _left_indexer^     

zIndex._left_indexerc                 C  r   r   )r   r   r   r   r   inner_join_indexerr   r   r   r   r   _inner_indexerl  r   zIndex._inner_indexerc                 C  r   r   )r   r   r   r   r   outer_join_indexerr   r   r   r   r   _outer_indexerz  r   zIndex._outer_indexerr   str_typExtensionArray | np.ndarray_datazDtype[ExtensionArray] | tuple[type[np.ndarray], type[ExtensionArray]]	_data_clsNzobject | None_idr	   _nameFr   _no_setting_namename	list[str]_comparables_attributes_is_numeric_dtypeT_can_hold_strings(_is_backward_compat_public_numeric_index;type[libindex.IndexEngine] | type[libindex.ExtensionEngine]c                 C  s   t jS r   )libindexObjectEnginer   r   r   r   _engine_type  s   zIndex._engine_typec                 K  s  |rt jdtt d ddlm} ddlm} t||| }|d ur%t	|}d|v r7|
d}	t||	 t|	}t||u rA| }t|trI|j}t|dd }
t|t|frj||||d}|d urh|j|d	d
S |S t|r| |}|tur||f|||d|S | }|j|||d}t| tj||dS t|
rtt|
}
| |
}|tur||f||d|}|d ur|j|d	d
S |S |d ur|j|d	d
}t| t|dd}tj||dS t|tr|jr|d u r|j |||dS t|t!j"tt#frit|t$r|j%}|d urt&|d ||d}|j'}|j'j(dv r!|}n1|j'j(dv r.t!)|}n$t*j+|t,d}|d u rRt-|dd}|j'}|rR| ||f||d|S | |j'}|.|||}t| |||S t/|rs| 0|t1|drtt!)|f|||d|S |rt2|rt3|rt4|}|rt5dd |D rddl6m7} |j8||p|9ddS t*j+|t,d}|d u rt-|d	d}|j'}t|f|||d|S )NzPassing keywords other than 'data', 'dtype', 'copy', 'name', 'tupleize_cols' is deprecated and will raise TypeError in a future version.  Use the specific Index subclass directly instead.
stacklevelr   PandasArray)
RangeIndextzr   )startcopyr   Fr   r   r   r   r   r   r   )r   r   Textract_numpyr   r   iuf)bcr   )cast_numeric_deprecated	__array__c                 s  s    | ]}t |tV  qd S r   )
isinstancetuple).0er   r   r   	<genexpr>,      z Index.__new__.<locals>.<genexpr>r   namesr  ):warningswarnFutureWarningr0   pandas.core.arraysr   pandas.core.indexes.ranger   maybe_extract_namerQ   r   rn   rm   typeto_numpyr	  rX   numpy_dtypegetattrrangeastyperA   _dtype_to_subclassr   construct_array_type_from_sequencer   _simple_newr   r"   rt   r   _constructorr   r   r_   r\   _valuesru   r   kindasarraycomasarray_tuplesafe
_dtype_obj_maybe_cast_data_without_dtype_ensure_arrayrL   _scalar_data_errorhasattrrI   rH   listallpandas.core.indexes.multir   from_tuplesget)r   r   r   r   r   tupleize_colsr   r   r   r   
data_dtyperesultr   ea_clsarrr   subarrr   r   r   r     s   











zIndex.__new__r   c                 C  s"   |j dkr	td|r| }|S )zF
        Ensure we have a valid array to pass to _simple_new.
        r   z Index data must be 1-dimensional)ndim
ValueErrorr   )r   r   r   r   r   r   r   r*  ?  s
   
zIndex._ensure_arrayr   r"   c           
      C  sP  t |trOt |trddlm} |S t |trddlm} |S t |tr,ddlm} |S t |t	r9ddlm
} |S t |trMtjdtt d | |jS tS |jdkr\ddlm} |S |jd	kridd
lm} |S t|ruddlm} |S t|rddlm} |S t|rddlm}	 |	S |tkrtS t|jtt t!j"t#t!j$t!j%frtS t&|)Nr   )DatetimeIndex)r   )IntervalIndex)PeriodIndexzIn a future version, passing a SparseArray to pd.Index will store that array directly instead of converting to a dense numpy ndarray. To retain the old behavior, use pd.Index(arr.to_numpy()) insteadr   Mm)TimedeltaIndex)Float64Index)UInt64Index)
Int64Index)'r	  rV   rU   pandasr:  rT   r   rW   r;  rY   r<  ro   r  r  r  r0   r  subtyper   r$  r?  rD   pandas.core.apir@  rO   rA  rM   rB  r(  r   r  r   r   r   bool_complex	complex64
complex128NotImplementedError)
r   r   r:  r   r;  r<  r?  r@  rA  rB  r   r   r   r  M  sV   







zIndex._dtype_to_subclassc                 C  s   t jdtt d dS )z
        Integer representation of the values.

        Returns
        -------
        ndarray
            An ndarray with int64 dtype.
        zAIndex.asi8 is deprecated and will be removed in a future version.r   N)r  r  r  r0   r   r   r   r   asi8  s   
z
Index.asi8r   type[_IndexT]c                 C  s@   t || jsJ t|t| }||_||_i |_|  |S )z
        We require that we have a dtype compat for the values. If we are passed
        a non-dtype compat, then coerce using the constructor.

        Must be careful not to recurse.
        )	r	  r   r  r   r   r   r   _cache_reset_identity)r   valuesr   r4  r   r   r   r!    s   
zIndex._simple_newc                 O  s~   t   t ddt | |i |}W d   n1 sw   Y  |jtkr=|js=t|j	}|jj
dv r=t||jdS |S )zw
        Constructor that uses the 1.0.x behavior inferring numeric dtypes
        for ndarray[object] inputs.
        ignorez.*the Index constructorN)r  r  r  r  r   )r  catch_warningsfilterwarningsr  r   r(  	_is_multir   maybe_convert_objectsr#  r$  r   r   )r   argsr   r4  rO  r   r   r   _with_infer  s   
zIndex._with_inferc                 C  s   t | S r   )r  r   r   r   r   r"       zIndex._constructorr   c                 C  s,   | j sd}|  }|d| 7 }t|dS )a:  
        Check that an Index has no duplicates.

        This is typically only called via
        `NDFrame.flags.allows_duplicate_labels.setter` when it's set to
        True (duplicates aren't allowed).

        Raises
        ------
        DuplicateLabelError
            When the index is not unique.
        zIndex has duplicates.
N)	is_unique_format_duplicate_messager)   )r   msg
duplicatesr   r   r   _maybe_check_unique  s   zIndex._maybe_check_uniquer   c                 C  s   ddl m} | | jdd  }t|sJ |tt| | t	| }| j
r3t| |j|_| jdkr=|d}|jddS )	a  
        Construct the DataFrame for a DuplicateLabelError.

        This returns a DataFrame indicating the labels and positions
        of duplicates in an index. This should only be called when it's
        already known that duplicates are present.

        Examples
        --------
        >>> idx = pd.Index(['a', 'b', 'a'])
        >>> idx._format_duplicate_message()
            positions
        label
        a        [0, 2]
        r   r   firstkeepr   label	positionsr   )rC  r   r   r   lenr   arangegroupbyaggr-  rS  r  r0  r   nlevelsrename_axisto_frame)r   r   r\  outr   r   r   rZ    s   "

zIndex._format_duplicate_messagedict[str_t, Any]c                   s&   t jdtt d  fdd jD S )z
        Return an attributes dict for my class.

        Temporarily added back for compatibility issue in dask, see
        https://github.com/pandas-dev/pandas/pull/43895
        z\The Index._get_attributes_dict method is deprecated, and will be removed in a future versionr   c                   s   i | ]	}|t  |d qS r   r  )r  kr   r   r   
<dictcomp>#  s    z.Index._get_attributes_dict.<locals>.<dictcomp>)r  r  DeprecationWarningr0   r   r   r   r   r   _get_attributes_dict  s   zIndex._get_attributes_dictc                 C  s    |t u r| jn|}| j||dS )az  
        Create a new Index with the same class as the caller, don't copy the
        data, use the same object attributes with passed in attributes taking
        precedence.

        *this is an internal non-public method*

        Parameters
        ----------
        values : the values to create the new Index, optional
        name : Label, defaults to self.name
        r   )r   r   r!  )r   rO  r   r   r   r   _shallow_copy%  s   zIndex._shallow_copyc                 C  s   | j | j| jd}| j|_|S )zR
        fastpath to make a shallow copy, i.e. new object with same data.
        r   )r!  r#  r   rM  r   r4  r   r   r   _view6  s   zIndex._viewc                 C  s   |   }||_|S )zG
        fastpath for rename if new name is already validated.
        )rt  r   )r   r   r4  r   r   r   _rename?  s   zIndex._renamec                 C  s>   | |u rdS t |dsdS | jdu s|jdu rdS | j|ju S )a  
        More flexible, faster check like ``is`` but that works through views.

        Note: this is *not* the same as ``Index.identical()``, which checks
        that metadata is also the same.

        Parameters
        ----------
        other : object
            Other object to compare against.

        Returns
        -------
        bool
            True if both have same underlying data, False otherwise.

        See Also
        --------
        Index.identical : Works like ``Index.is_`` but also checks metadata.
        Tr   FN)r,  r   r   r   r   r   r   is_H  s   
z	Index.is_c                 C  s   t  | _dS )zJ
        Initializes or resets ``_id`` attribute with new object.
        N)r   r   r   r   r   r   rN  g  s   zIndex._reset_identityc                 C  s   | j   d S r   )_engineclear_mappingr   r   r   r   _cleanupn  s   zIndex._cleanup/libindex.IndexEngine | libindex.ExtensionEnginec                 C  s~   |   }t|tr| jtju rt|S ttj	|}|j
tkr$t|S |j
tjkr/t|S |j
tjkr:t|S | |S r   )r   r	  rl   r   r   r   ExtensionEnginer   r   r   r   r   
BoolEnginerH  Complex64EnginerI  Complex128Engine)r   target_valuesr   r   r   rx  r  s   






zIndex._engine
set[str_t]c                 C  s"   dd | j dddtd D S )z
        Add the string-like labels to the owner dataframe/series dir output.

        If this is a MultiIndex, it's first level values are used.
        c                 S  s"   h | ]}t |tr| r|qS r   )r	  r   isidentifierr  r  r   r   r   	<setcomp>  s    z1Index._dir_additions_for_owner.<locals>.<setcomp>r   r   Nzdisplay.max_dir_items)r   r   r   r   r   r   _dir_additions_for_owner  s   zIndex._dir_additions_for_ownerintc                 C  
   t | jS )z1
        Return the length of the Index.
        )rd  r   r   r   r   r   __len__  s   
zIndex.__len__r   c                 C  s   t j| j|dS )z8
        The array interface, return my values.
        r  )r   r%  r   r   r   r   r   r   r    s   zIndex.__array__ufuncnp.ufuncmethodr   c                   s   t dd |D rtS |dkr|tjtjtjfv s-tj ||g|R i |}|tur-|S d|v r?tj ||g|R i |S |dkrWtj	 ||g|R i |}|turW|S  fdd|D }t
|||i |}|jdkrzt fd	d|D S  |S )
Nc                 s  s    | ]
}t |ttfV  qd S r   )r	  r_   rZ   )r  r   r   r   r   r    s    z(Index.__array_ufunc__.<locals>.<genexpr>__call__rk  reducec                   s   g | ]}| ur
|n|j qS r   r#  r  xr   r   r   
<listcomp>      z)Index.__array_ufunc__.<locals>.<listcomp>   c                 3      | ]}  |V  qd S r   )__array_wrap__r  r   r   r   r    r  )anyNotImplementedr   bitwise_and
bitwise_orbitwise_xorre   !maybe_dispatch_ufunc_to_dunder_opdispatch_ufunc_with_outdispatch_reduction_ufuncr  noutr
  r  )r   r  r  inputsr   r4  
new_inputsr   r   r   __array_ufunc__  sL   

zIndex.__array_ufunc__c                 C  s<   t |}t|st |st|dkr|S t|| jdS )zN
        Gets called after a ufunc and other functions e.g. np.split.
        r   r   )r   item_from_zerodimr>   rL   r   r8  r   r   )r   r4  contextr   r   r   r    s   
 zIndex.__array_wrap__c                 C     | j jS )zA
        Return the dtype object of the underlying data.
        )r   r   r   r   r   r   r        zIndex.dtypeCc                 C  sR   t jdtt d t| jr| jj}nt| jrt	
| j}n|  }|j|dS )a  
        Return an ndarray of the flattened values of the underlying data.

        Returns
        -------
        numpy.ndarray
            Flattened array.

        See Also
        --------
        numpy.ndarray.ravel : Return a flattened array.
        zaIndex.ravel returning ndarray is deprecated; in a future version this will return a view on self.r   )order)r  r  r  r0   rP   r   r   _ndarrayrG   r   r%  r   ravel)r   r  rO  r   r   r   r    s   


zIndex.ravelc                 C  s   |d urPt |dsP|}t|trt|}t|tjtfrIt|rI|jdkr/|dkr/| j	
|S | |}|j}|| j	
d|d}|j|| jdS | j	
|}n|  }t|tr]| j|_|S )Nr   r>  zm8[ns]i8r  r   )r,  r	  r   rQ   r   r   rV   rP   r$  r   viewr  r   r!  r   rt  r   r   )r   r   r   idx_clsarr_clsr6  r4  r   r   r   r     s$   


z
Index.viewc              
   C  s  |durt |}t| j|r|r|  S | S | j}t|tr[t|tjr8|jdkr8t	|r8t
dt| j dtt|jt| j |j||d}W d   n1 sUw   Y  nht| jrlt|rlt
d| dt|tr~| }|j| ||d}nEz|tkr|j||d}nt|||d}W n/ ty     t
tfy } z|jd	krd
t|v r t
dt| j d| |d}~ww | jrt|tjrt|r| j|| j|ddS t|| j|jddS )a[  
        Create an Index with values cast to dtypes.

        The class of a new Index is determined by dtype. When conversion is
        impossible, a TypeError exception is raised.

        Parameters
        ----------
        dtype : numpy dtype or pandas type
            Note that any signed integer `dtype` is treated as ``'int64'``,
            and any unsigned integer `dtype` is treated as ``'uint64'``,
            regardless of the size.
        copy : bool, default True
            By default, astype always returns a newly allocated object.
            If copy is set to False and internal requirements on dtype are
            satisfied, the original data is used to create a new Index
            or the original Index is returned.

        Returns
        -------
        Index
            Index with values cast to specified dtype.
        Nr=  zCannot cast z	 to dtyper   z%Cannot convert Float64Index to dtype z,; integer values are required for conversionr   r  
losslesslyz
 to dtype F)r   r   r   )rQ   r@   r   r   r   r	  rl   r   r$  r   r   r  __name__r1   r  rD   rP   rV   r  r   r   r2   r*   r9  r   rJ   r"  r   r   )r   r   r   rO  
new_valuesr   errr   r   r   r    sT   


	
zIndex.astypeas  
        Return a new %(klass)s of the values selected by the indices.

        For internal compatibility with numpy arrays.

        Parameters
        ----------
        indices : array-like
            Indices to be taken.
        axis : int, optional
            The axis over which to select values, always 0.
        allow_fill : bool, default True
        fill_value : scalar, default None
            If allow_fill=True and fill_value is not None, indices specified by
            -1 are regarded as NA. If Index doesn't hold NA, raise ValueError.

        Returns
        -------
        Index
            An index formed of elements at the given indices. Will be the same
            type as self, except for RangeIndex.

        See Also
        --------
        numpy.ndarray.take: Return an array formed from the
            elements of a at the given indices.
        taker   axis
allow_fillc                 K  s   |rt d| t|rtdt|}| |||}| j}t|tj	r/t
j|||| jd}n	|j||| jd}| jj|| jdS )Nr   z!Expected indices to be array-like)r  
fill_valuer   )nvvalidate_takerL   r   r=   _maybe_disallow_fillr#  r	  r   r   r   r  	_na_valuer"  r!  r   )r   indicesr  r  r  r   rO  takenr   r   r   r    s   
z
Index.takec                 C  sL   |r"|dur"| j r|dk  rtd|S t| j}td| dd}|S )zm
        We only use pandas-style take when allow_fill is True _and_
        fill_value is not None.
        NzJWhen allow_fill=True and fill_value is not None, all indices must be >= -1zUnable to fill values because z cannot contain NAF)_can_hold_nar  r9  r  r  )r   r  r  r  cls_namer   r   r   r    s   

zIndex._maybe_disallow_filla  
        Repeat elements of a %(klass)s.

        Returns a new %(klass)s where each element of the current %(klass)s
        is repeated consecutively a given number of times.

        Parameters
        ----------
        repeats : int or array of ints
            The number of repetitions for each element. This should be a
            non-negative integer. Repeating 0 times will return an empty
            %(klass)s.
        axis : None
            Must be ``None``. Has no effect but is accepted for compatibility
            with numpy.

        Returns
        -------
        repeated_index : %(klass)s
            Newly created %(klass)s with repeated elements.

        See Also
        --------
        Series.repeat : Equivalent function for Series.
        numpy.repeat : Similar method for :class:`numpy.ndarray`.

        Examples
        --------
        >>> idx = pd.Index(['a', 'b', 'c'])
        >>> idx
        Index(['a', 'b', 'c'], dtype='object')
        >>> idx.repeat(2)
        Index(['a', 'a', 'b', 'b', 'c', 'c'], dtype='object')
        >>> idx.repeat([1, 2, 3])
        Index(['a', 'b', 'b', 'c', 'c', 'c'], dtype='object')
        repeatc                 C  s6   t |}tdd|i | j|}| jj|| jdS )Nr   r  r   )r=   r  validate_repeatr#  r  r"  r!  r   )r   repeatsr  
res_valuesr   r   r   r    s   zIndex.repeatHashable | NonedeepDtype | Noner  Sequence[Hashable] | Nonec                 C  s   |durt jdtt d | j|||dd }|r(| j }t| j||d}n| j	|d}|r>t jdtt d |
|}|S )a  
        Make a copy of this object.

        Name and dtype sets those attributes on the new object.

        Parameters
        ----------
        name : Label, optional
            Set name for new object.
        deep : bool, default False
        dtype : numpy dtype or pandas type, optional
            Set dtype for new object.

            .. deprecated:: 1.2.0
                use ``astype`` method instead.
        names : list-like, optional
            Kept for compatibility with MultiIndex. Should not be used.

            .. deprecated:: 1.4.0
                use ``name`` instead.

        Returns
        -------
        Index
            Index refer to new object which is a copy of this object.

        Notes
        -----
        In most cases, there should be no functional difference from using
        ``deep``, but if ``deep`` is passed it will attempt to deepcopy.
        Nzfparameter names is deprecated and will be removed in a future version. Use the name parameter instead.r   )r   r  r  r   r   zeparameter dtype is deprecated and will be removed in a future version. Use the astype method instead.)r  r  r  r0   _validate_namesr   r   r  r!  ru  r  )r   r   r  r   r  new_data	new_indexr   r   r   r     s&   &

z
Index.copyc                 K  s   | j di |S )Nr   r   )r   r   r   r   r   __copy__4  s   zIndex.__copy__c                 C  s   | j ddS )zq
        Parameters
        ----------
        memo, default None
            Standard signature. Unused
        Tr  r   )r   memor   r   r   __deepcopy__8  s   zIndex.__deepcopy__c                 C  s`   t | j}|  }|  }|  }dd |D }d| |}|du r&d}| d| | dS )zA
        Return a string representation for this object.
        c                 S  s   g | ]\}}| d | qS )=r   r  rn  vr   r   r   r  N  r  z"Index.__repr__.<locals>.<listcomp>,Nr   ())r  r  _format_data_format_attrs_format_spacer   )r   
klass_namer   attrsspace	attrs_strpreprr   r   r   __repr__E  s   
zIndex.__repr__c                 C     dS )N r   r   r   r   r   r  W  s   zIndex._format_spacec                 C  s   t S )z0
        Return the formatter function.
        )r   r   r   r   r   _formatter_funca     zIndex._formatter_funcc                 C  sL   d}| j dkr
d}n| j dkrtd| } t| jrd}t| | j||| jdS )z@
        Return the formatted data as a unicode string.
        TstringFcategoricalr   )
is_justifyr   line_break_each_value)inferred_typer   rK   
categoriesr   r  rS  )r   r   r  r   r   r   r  h  s   



zIndex._format_data-list[tuple[str_t, str_t | int | bool | None]]c                 C  s   g }| j s|dd| j df | jdur!|dt| jf n| j r8tdd | jD r8|dt| jf tdp?t| }t| |krO|d	t| f |S )
zH
        Return a list of tuples of the (attr,formatted_value).
        r   'Nr   c                 s  s    | ]}|d uV  qd S r   r   r  r   r   r   r        z&Index._format_attrs.<locals>.<genexpr>r  zdisplay.max_seq_itemslength)	rS  appendr   r   r   r  r  r   rd  )r   r  max_seq_itemsr   r   r   r  ~  s   
zIndex._format_attrsHashable | Sequence[Hashable]c                 C  s.   | j rdd t| jD S | jdu rdS | jS )zX
        Return a name or list of names with None replaced by the level number.
        c                 S  s    g | ]\}}|d u r|n|qS r   r   )r  r   r   r   r   r   r    s    z*Index._get_level_names.<locals>.<listcomp>Nr   )rS  	enumerater  r   r   r   r   r   _get_level_names  s
   zIndex._get_level_namesc                 C  s8   t | jtjr| jjdkrttj| jS | jtddj	S )Nr=  Fr   )
r	  r   r   r$  r   r   rO  r  r   r#  r   r   r   r   	_mpl_repr  s   zIndex._mpl_reprNaN	formatterCallable | Nonena_replist[str_t]c                 C  sR   g }|r| | jdurt| jddnd |dur"|t| | S | j||dS )z>
        Render a string representation of the Index.
        N	rX  escape_charsr   )r  )r  r   r   r-  map_format_with_header)r   r   r  r  headerr   r   r   format  s   	zIndex.formatr  c                 C  s   ddl m} | j}t|jr;ttj|}tj	|dd}dd |D }t
|}| r7t|}|||< | }|| S t||d dd}|| S )	Nr   )format_arrayT)safec                 S  s   g | ]}t |d dqS )r  r  )r   r  r   r   r   r        z-Index._format_with_header.<locals>.<listcomp>r   )justify)pandas.io.formats.formatr  r#  rK   r   r   r   r   r   rT  r   r  arraytolist
trim_front)r   r  r  r  rO  r4  mask
result_arrr   r   r   r    s   

zIndex._format_with_headerc                 K  s6   t jdtt d | }|dur|| }|jdi |S )a(  
        Format specified values of `self` and return them.

        .. deprecated:: 1.2.0

        Parameters
        ----------
        slicer : int, array-like
            An indexer into `self` that specifies which values
            are used in the formatting process.
        kwargs : dict
            Options for specifying how the values should be formatted.
            These options include the following:

            1) na_rep : str
                The value that serves as a placeholder for NULL values
            2) quoting : bool or None
                Whether or not there are quoted values in `self`
            3) date_format : str
                The format used to represent date-like values.

        Returns
        -------
        numpy.ndarray
            Formatted values.
        znThe 'to_native_types' method is deprecated and will be removed in a future version. Use 'astype(str)' instead.r   Nr   )r  r  r  r0   _format_native_types)r   slicerr   rO  r   r   r   to_native_types  s   zIndex.to_native_typesr   )r  quotingnpt.NDArray[np.object_]c                K  sB   t | }|  s|st| t}ntj| tdd}|||< |S )z>
        Actually format specific types of the index.
        Tr   )rd   	is_objectr   r%  r  r   r  r   )r   r  r  r   r	  rO  r   r   r   r    s   zIndex._format_native_typesc                 C  s   t | dkrQ| d }t|drt|ts| }nt| jr'| |dd}| d }t|dr:t|ts:| }nt| jrH| |dd}d| d| }nd}|du r\t	| j
}| d	t |  d
| S )a  
        Return a summarized representation.

        Parameters
        ----------
        name : str
            name to use in the summary representation

        Returns
        -------
        String with a summarized representation of the index
        r   r   r  r   r  z, z to Nz: z entries)rd  r,  r	  r   r   rP   r   r  replacer  r  )r   r   headtailindex_summaryr   r   r   _summary  s    




zIndex._summaryc                 C     | S )a+  
        Identity method.

        This is implemented for compatibility with subclass implementations
        when chaining.

        Returns
        -------
        pd.Index
            Caller.

        See Also
        --------
        MultiIndex.to_flat_index : Subclass implementation.
        r   r   r   r   r   to_flat_index+  s   zIndex.to_flat_indexr   c                 C  s>   ddl m} |du r|  }|du r| j}|| j ||dS )a  
        Create a Series with both index and values equal to the index keys.

        Useful with map for returning an indexer based on an index.

        Parameters
        ----------
        index : Index, optional
            Index of resulting Series. If None, defaults to original index.
        name : str, optional
            Name of resulting Series. If None, defaults to name of original
            index.

        Returns
        -------
        Series
            The dtype will be based on the type of the Index values.

        See Also
        --------
        Index.to_frame : Convert an Index to a DataFrame.
        Series.to_frame : Convert Series to DataFrame.

        Examples
        --------
        >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')

        By default, the original Index and original name is reused.

        >>> idx.to_series()
        animal
        Ant      Ant
        Bear    Bear
        Cow      Cow
        Name: animal, dtype: object

        To enforce a new Index, specify new labels to ``index``:

        >>> idx.to_series(index=[0, 1, 2])
        0     Ant
        1    Bear
        2     Cow
        Name: animal, dtype: object

        To override the name of the resulting column, specify `name`:

        >>> idx.to_series(name='zoo')
        animal
        Ant      Ant
        Bear    Bear
        Cow      Cow
        Name: zoo, dtype: object
        r   r^  N)r   r   )rC  r   rt  r   r#  r   )r   r   r   r   r   r   r   	to_series=  s   6zIndex.to_seriesc                 C  s^   ddl m} |du rtjdtt d tj}|tju r|  }||| j	
 i}|r-| |_|S )a  
        Create a DataFrame with a column containing the Index.

        Parameters
        ----------
        index : bool, default True
            Set the index of the returned DataFrame as the original Index.

        name : object, default None
            The passed name should substitute for the index name (if it has
            one).

        Returns
        -------
        DataFrame
            DataFrame containing the original Index data.

        See Also
        --------
        Index.to_series : Convert an Index to a Series.
        Series.to_frame : Convert Series to DataFrame.

        Examples
        --------
        >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal')
        >>> idx.to_frame()
               animal
        animal
        Ant       Ant
        Bear     Bear
        Cow       Cow

        By default, the original Index is reused. To enforce a new Index:

        >>> idx.to_frame(index=False)
            animal
        0   Ant
        1  Bear
        2   Cow

        To override the name of the resulting column, specify `name`:

        >>> idx.to_frame(index=False, name='zoo')
            zoo
        0   Ant
        1  Bear
        2   Cow
        r   )r   NzExplicitly passing `name=None` currently preserves the Index's name or uses a default name of 0. This behaviour is deprecated, and in the future `None` will be used as the name of the resulting DataFrame column.r   )rC  r   r  r  r  r0   r   r   r  r#  r   r   )r   r   r   r   r4  r   r   r   rj  |  s   3
zIndex.to_framec                 C     | j S )z2
        Return Index or MultiIndex name.
        )r   r   r   r   r   r     s   z
Index.namevaluec                 C  s(   | j rtdt|d t|  || _d S )NzOCannot set name on a level of a MultiIndex. Use 'MultiIndex.set_names' instead.)r   RuntimeErrorr  r  r   r   r  r   r   r   r     s   
list[Hashable]c                 C  s   ddl m} |dur|durtd|du r%|du r%|r!|| jn| j}n|dur4t|s1td|}n
t|s<|g}n|}t|t| jkrVtdt| j dt| t|dt| j	 d	i |S )
z
        Handles the quirks of having a singular 'name' parameter for general
        Index and plural 'names' parameter for MultiIndex.
        r   )deepcopyNz*Can only provide one of `names` and `name`Must pass list-like as `names`.zLength of new names must be z, got 
error_name.name)
r   r  r   r  rI   rd  r9  rR   r  r  )r   r   r  r  r  	new_namesr   r   r   r    s$   zIndex._validate_names$Hashable | Sequence[Hashable] | Nonec                 C  s   ddl m} |durt|tst|tr|g}t|ts$|dur$td|s?t| |r3t| j	}|S | j
du r;|gn| j
g}|S )a=  
        Get names of index.

        Parameters
        ----------
        names : int, str or 1-dimensional list, default None
            Index names to set.
        default : str
            Default name of index.

        Raises
        ------
        TypeError
            if names not str or list-like
        r   r  Nz-Index names must be str or 1-dimensional list)r/  r   r	  r   r  r-  r9  r&  fill_missing_namesr  r   )r   r  defaultr   r   r   r   _get_default_index_names  s   
zIndex._get_default_index_namesrw   c                 C  s   t | jfS r   )rw   r   r   r   r   r   
_get_names     zIndex._get_namesr  c                C  sV   t |stdt|dkrtdt| t|dt| j di |d | _dS )a  
        Set new names on index. Each name has to be a hashable type.

        Parameters
        ----------
        values : str or sequence
            name(s) to set
        level : int, level name, or sequence of int/level names (default None)
            If the index is a MultiIndex (hierarchical), level(s) to set (None
            for all levels).  Otherwise level must be None

        Raises
        ------
        TypeError if each name is not hashable.
        zNames must be a list-liker   z#Length of new names must be 1, got r   r!  r   N)rI   r9  rd  rR   r  r  r   r   rO  r   r   r   r   
_set_names   s   zIndex._set_names)fsetfget)versionallowed_argsr   c                 C  s>  |durt | tstd|durt|st|rtdt|s.|du r.| jdkr.tdt|r;t | ts;tdt|rG|durGtdt | trwt|rw|du rwg g }}t| jD ]\}}||	 v rt|
| |
||  q^|}t|s~|g}|durt|s|g}|r| }n|  }|j||d |s|S dS )	a  
        Set Index or MultiIndex name.

        Able to set new names partially and by level.

        Parameters
        ----------

        names : label or list of label or dict-like for MultiIndex
            Name(s) to set.

            .. versionchanged:: 1.3.0

        level : int, label or list of int or label, optional
            If the index is a MultiIndex and names is not dict-like, level(s) to set
            (None for all levels). Otherwise level must be None.

            .. versionchanged:: 1.3.0

        inplace : bool, default False
            Modifies the object directly, instead of creating a new Index or
            MultiIndex.

        Returns
        -------
        Index or None
            The same type as the caller or None if ``inplace=True``.

        See Also
        --------
        Index.rename : Able to set new names without level.

        Examples
        --------
        >>> idx = pd.Index([1, 2, 3, 4])
        >>> idx
        Int64Index([1, 2, 3, 4], dtype='int64')
        >>> idx.set_names('quarter')
        Int64Index([1, 2, 3, 4], dtype='int64', name='quarter')

        >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],
        ...                                   [2018, 2019]])
        >>> idx
        MultiIndex([('python', 2018),
                    ('python', 2019),
                    ( 'cobra', 2018),
                    ( 'cobra', 2019)],
                   )
        >>> idx.set_names(['kind', 'year'], inplace=True)
        >>> idx
        MultiIndex([('python', 2018),
                    ('python', 2019),
                    ( 'cobra', 2018),
                    ( 'cobra', 2019)],
                   names=['kind', 'year'])
        >>> idx.set_names('species', level=0)
        MultiIndex([('python', 2018),
                    ('python', 2019),
                    ( 'cobra', 2018),
                    ( 'cobra', 2019)],
                   names=['species', 'year'])

        When renaming levels with a dict, levels can not be passed.

        >>> idx.set_names({'kind': 'snake'})
        MultiIndex([('python', 2018),
                    ('python', 2019),
                    ( 'cobra', 2018),
                    ( 'cobra', 2019)],
                   names=['snake', 'year'])
        Nz%Level must be None for non-MultiIndexz7Names must be a string when a single level is provided.r   r  z2Can only pass dict-like as `names` for MultiIndex.z(Can not pass level for dictlike `names`.r  )r	  r\   r9  rI   r   rh  ra   r  r  keysr  rt  r*  )r   r  r   r   names_adjustedr  r   idxr   r   r   	set_names=  s:   I

zIndex.set_namesc                 C  s   | j |g|dS )aq  
        Alter Index or MultiIndex name.

        Able to set new names without level. Defaults to returning new index.
        Length of names must match number of levels in MultiIndex.

        Parameters
        ----------
        name : label or list of labels
            Name(s) to set.
        inplace : bool, default False
            Modifies the object directly, instead of creating a new Index or
            MultiIndex.

        Returns
        -------
        Index or None
            The same type as the caller or None if ``inplace=True``.

        See Also
        --------
        Index.set_names : Able to set new names partially and by level.

        Examples
        --------
        >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score')
        >>> idx.rename('grade')
        Index(['A', 'C', 'A', 'B'], dtype='object', name='grade')

        >>> idx = pd.MultiIndex.from_product([['python', 'cobra'],
        ...                                   [2018, 2019]],
        ...                                   names=['kind', 'year'])
        >>> idx
        MultiIndex([('python', 2018),
                    ('python', 2019),
                    ( 'cobra', 2018),
                    ( 'cobra', 2019)],
                   names=['kind', 'year'])
        >>> idx.rename(['species', 'year'])
        MultiIndex([('python', 2018),
                    ('python', 2019),
                    ( 'cobra', 2018),
                    ( 'cobra', 2019)],
                   names=['species', 'year'])
        >>> idx.rename('species')
        Traceback (most recent call last):
        TypeError: Must pass list-like as `names`.
        )r   )r2  )r   r   r   r   r   r   rename  s   1zIndex.renamec                 C  r  )z#
        Number of levels.
        r   r   r   r   r   r   rh    r  zIndex.nlevelsc                 C  r  )z)
        Compat with MultiIndex.
        r   r   r   r   r   _sort_levels_monotonic     zIndex._sort_levels_monotonicc                 C  sn   t |tr$|dk r|dkrtd| d|dkr"td|d  d
S || jkr5td| d| j d	d
S )z
        Validate index level.

        For single-level Index getting level number is a no-op, but some
        verification must be done like in MultiIndex.

        r   r  z)Too many levels: Index has only 1 level, z is not a valid level numberz-Too many levels: Index has only 1 level, not r   zRequested level (z) does not match index name (r  N)r	  r  
IndexErrorr   KeyErrorr   r   r   r   r   _validate_index_level  s"   
	
zIndex._validate_index_levelc                 C  s   |  | dS )Nr   r9  r8  r   r   r   _get_level_number  s   
zIndex._get_level_numberc                 C  s\   t |ttfstdt |trt|dkrtd|d }t |ts'td| jd|dS )a\  
        For internal compatibility with the Index API.

        Sort the Index. This is for compat with MultiIndex

        Parameters
        ----------
        ascending : bool, default True
            False to sort in descending order

        level, sort_remaining are compat parameters

        Returns
        -------
        Index
        zIascending must be a single bool value ora list of bool values of length 1r   z3ascending must be a list of bool values of length 1r   zascending must be a bool valueT)return_indexer	ascending)r	  r-  r   r   rd  sort_values)r   r   r=  sort_remainingr   r   r   	sortlevel  s   

zIndex.sortlevelc                 C  s   |  | | S )a  
        Return an Index of values for requested level.

        This is primarily useful to get an individual level of values from a
        MultiIndex, but is provided on Index as well for compatibility.

        Parameters
        ----------
        level : int or str
            It is either the integer position or the name of the level.

        Returns
        -------
        Index
            Calling object, as there is only one level in the Index.

        See Also
        --------
        MultiIndex.get_level_values : Get values for a level of a MultiIndex.

        Notes
        -----
        For Index, level should be 0, since there are no multiple levels.

        Examples
        --------
        >>> idx = pd.Index(list('abc'))
        >>> idx
        Index(['a', 'b', 'c'], dtype='object')

        Get level values by supplying `level` as integer:

        >>> idx.get_level_values(0)
        Index(['a', 'b', 'c'], dtype='object')
        r:  r8  r   r   r   _get_level_values,  s   
$zIndex._get_level_valuesc                   s>   t |ttfs
|g}t fdd|D ddd } |S )a  
        Return index with requested level(s) removed.

        If resulting index has only 1 level left, the result will be
        of Index type, not MultiIndex.

        Parameters
        ----------
        level : int, str, or list-like, default 0
            If a string is given, must be the name of a level
            If list-like, elements must be names or indexes of levels.

        Returns
        -------
        Index or MultiIndex

        Examples
        --------
        >>> mi = pd.MultiIndex.from_arrays(
        ... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z'])
        >>> mi
        MultiIndex([(1, 3, 5),
                    (2, 4, 6)],
                   names=['x', 'y', 'z'])

        >>> mi.droplevel()
        MultiIndex([(3, 5),
                    (4, 6)],
                   names=['y', 'z'])

        >>> mi.droplevel(2)
        MultiIndex([(1, 3),
                    (2, 4)],
                   names=['x', 'y'])

        >>> mi.droplevel('z')
        MultiIndex([(1, 3),
                    (2, 4)],
                   names=['x', 'y'])

        >>> mi.droplevel(['x', 'y'])
        Int64Index([5, 6], dtype='int64', name='z')
        c                 3  r  r   )r;  )r  levr   r   r   r    r  z"Index.droplevel.<locals>.<genexpr>Nr  )r	  r
  r-  sorted_drop_level_numbers)r   r   levnumsr   r   r   	droplevelU  s   - 
zIndex.droplevelrE  	list[int]c                 C  sX  |s	t | ts	| S t|| jkrtdt| d| j dtd| } t| j}t| j}t| j	}|D ]}|
| |
| |
| q4t|dkr|d }t|dkr}t|d dkrf|dd }|S tj|j|d dd	}|jj||d d
}|S |d dk}	|d |d }|	 r||	tj}|d |_|S ddlm}
 |
|||ddS )zE
        Drop MultiIndex levels by level _number_, not name.
        zCannot remove z levels from an index with z) levels: at least one level must be left.r   r   r   NT)r  r   r  r  Flevelsr   r  r   )r	  r\   rd  rh  r9  r   r-  rI  r   r  r   r   r  r#  r"  r!  r  putmaskr   nanr   r/  r   )r   rE  
new_levels	new_codesr"  r  rB  r4  r  r	  r   r   r   r   rD    sL   







zIndex._drop_level_numbers)r   dropnarN  @tuple[Index, npt.NDArray[np.signedinteger] | None, Index | None]c                C  s6   |du s
|dks
J |du r| }n|  |}|ddfS )aJ  
        Get index grouper corresponding to an index level

        Parameters
        ----------
        mapper: Group mapping function or None
            Function mapping index values to groups
        level : int or None
            Index level, positional
        dropna : bool
            dropna from groupby

        Returns
        -------
        grouper : Index
            Index of values to group on.
        labels : ndarray of int or None
            Array of locations in level_index.
        uniques : Index or None
            Index of unique values for level.
        Nr   )r  )r   mapperr   rN  grouperr   r   r   _get_grouper_for_level  s
   

zIndex._get_grouper_for_levelc                 C  s8   t | jtrt | jtrdS | jjS | jjdv rdS dS )NT)r  r  r  F)r	  r   rV   rW   r  r$  r   r   r   r   r    s   zIndex._can_hold_nac                 C     t jdtt d | jS )z
        Alias for is_monotonic_increasing.

        .. deprecated:: 1.5.0
            is_monotonic is deprecated and will be removed in a future version.
            Use is_monotonic_increasing instead.
        zhis_monotonic is deprecated and will be removed in a future version. Use is_monotonic_increasing instead.r   )r  r  r  r0   is_monotonic_increasingr   r   r   r   is_monotonic  s   
zIndex.is_monotonicc                 C  r  )a3  
        Return a boolean if the values are equal or increasing.

        Examples
        --------
        >>> Index([1, 2, 3]).is_monotonic_increasing
        True
        >>> Index([1, 2, 2]).is_monotonic_increasing
        True
        >>> Index([1, 3, 2]).is_monotonic_increasing
        False
        )rx  rT  r   r   r   r   rT  
	     zIndex.is_monotonic_increasingc                 C  r  )a3  
        Return a boolean if the values are equal or decreasing.

        Examples
        --------
        >>> Index([3, 2, 1]).is_monotonic_decreasing
        True
        >>> Index([3, 2, 2]).is_monotonic_decreasing
        True
        >>> Index([3, 1, 2]).is_monotonic_decreasing
        False
        )rx  is_monotonic_decreasingr   r   r   r   rW  	  rV  zIndex.is_monotonic_decreasingc                 C     | j o| jS )aq  
        Return if the index is strictly monotonic increasing
        (only increasing) values.

        Examples
        --------
        >>> Index([1, 2, 3])._is_strictly_monotonic_increasing
        True
        >>> Index([1, 2, 2])._is_strictly_monotonic_increasing
        False
        >>> Index([1, 3, 2])._is_strictly_monotonic_increasing
        False
        )rY  rT  r   r   r   r   !_is_strictly_monotonic_increasing*	     z'Index._is_strictly_monotonic_increasingc                 C  rX  )aq  
        Return if the index is strictly monotonic decreasing
        (only decreasing) values.

        Examples
        --------
        >>> Index([3, 2, 1])._is_strictly_monotonic_decreasing
        True
        >>> Index([3, 2, 2])._is_strictly_monotonic_decreasing
        False
        >>> Index([3, 1, 2])._is_strictly_monotonic_decreasing
        False
        )rY  rW  r   r   r   r   !_is_strictly_monotonic_decreasing<	  rZ  z'Index._is_strictly_monotonic_decreasingc                 C  r  )z8
        Return if the index has unique values.
        )rx  rY  r   r   r   r   rY  N	  r  zIndex.is_uniquec                 C  s   | j  S )a  
        Check if the Index has duplicate values.

        Returns
        -------
        bool
            Whether or not the Index has duplicate values.

        Examples
        --------
        >>> idx = pd.Index([1, 5, 7, 7])
        >>> idx.has_duplicates
        True

        >>> idx = pd.Index([1, 5, 7])
        >>> idx.has_duplicates
        False

        >>> idx = pd.Index(["Watermelon", "Orange", "Apple",
        ...                 "Watermelon"]).astype("category")
        >>> idx.has_duplicates
        True

        >>> idx = pd.Index(["Orange", "Apple",
        ...                 "Watermelon"]).astype("category")
        >>> idx.has_duplicates
        False
        rY  r   r   r   r   has_duplicatesU	  s   zIndex.has_duplicatesc                 C  
   | j dv S )a  
        Check if the Index only consists of booleans.

        Returns
        -------
        bool
            Whether or not the Index only consists of booleans.

        See Also
        --------
        is_integer : Check if the Index only consists of integers.
        is_floating : Check if the Index is a floating type.
        is_numeric : Check if the Index only consists of numeric data.
        is_object : Check if the Index is of the object dtype.
        is_categorical : Check if the Index holds categorical data.
        is_interval : Check if the Index holds Interval objects.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index([True, False, True])
        >>> idx.is_boolean()
        True

        >>> idx = pd.Index(["True", "False", "True"])
        >>> idx.is_boolean()
        False

        >>> idx = pd.Index([True, False, "True"])
        >>> idx.is_boolean()
        False
        )booleanr  r   r   r   r   
is_booleanv	     
"zIndex.is_booleanc                 C  r^  )a  
        Check if the Index only consists of integers.

        Returns
        -------
        bool
            Whether or not the Index only consists of integers.

        See Also
        --------
        is_boolean : Check if the Index only consists of booleans.
        is_floating : Check if the Index is a floating type.
        is_numeric : Check if the Index only consists of numeric data.
        is_object : Check if the Index is of the object dtype.
        is_categorical : Check if the Index holds categorical data.
        is_interval : Check if the Index holds Interval objects.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index([1, 2, 3, 4])
        >>> idx.is_integer()
        True

        >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
        >>> idx.is_integer()
        False

        >>> idx = pd.Index(["Apple", "Mango", "Watermelon"])
        >>> idx.is_integer()
        False
        )integerr`  r   r   r   r   rF   	  rb  zIndex.is_integerc                 C  r^  )a  
        Check if the Index is a floating type.

        The Index may consist of only floats, NaNs, or a mix of floats,
        integers, or NaNs.

        Returns
        -------
        bool
            Whether or not the Index only consists of only consists of floats, NaNs, or
            a mix of floats, integers, or NaNs.

        See Also
        --------
        is_boolean : Check if the Index only consists of booleans.
        is_integer : Check if the Index only consists of integers.
        is_numeric : Check if the Index only consists of numeric data.
        is_object : Check if the Index is of the object dtype.
        is_categorical : Check if the Index holds categorical data.
        is_interval : Check if the Index holds Interval objects.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
        >>> idx.is_floating()
        True

        >>> idx = pd.Index([1.0, 2.0, np.nan, 4.0])
        >>> idx.is_floating()
        True

        >>> idx = pd.Index([1, 2, 3, 4, np.nan])
        >>> idx.is_floating()
        True

        >>> idx = pd.Index([1, 2, 3, 4])
        >>> idx.is_floating()
        False
        )floatingzmixed-integer-floatz
integer-nar`  r   r   r   r   is_floating	     
*zIndex.is_floatingc                 C  r^  )a  
        Check if the Index only consists of numeric data.

        Returns
        -------
        bool
            Whether or not the Index only consists of numeric data.

        See Also
        --------
        is_boolean : Check if the Index only consists of booleans.
        is_integer : Check if the Index only consists of integers.
        is_floating : Check if the Index is a floating type.
        is_object : Check if the Index is of the object dtype.
        is_categorical : Check if the Index holds categorical data.
        is_interval : Check if the Index holds Interval objects.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
        >>> idx.is_numeric()
        True

        >>> idx = pd.Index([1, 2, 3, 4.0])
        >>> idx.is_numeric()
        True

        >>> idx = pd.Index([1, 2, 3, 4])
        >>> idx.is_numeric()
        True

        >>> idx = pd.Index([1, 2, 3, 4.0, np.nan])
        >>> idx.is_numeric()
        True

        >>> idx = pd.Index([1, 2, 3, 4.0, np.nan, "Apple"])
        >>> idx.is_numeric()
        False
        )rc  rd  r`  r   r   r   r   
is_numeric	  rf  zIndex.is_numericc                 C  r  )a  
        Check if the Index is of the object dtype.

        Returns
        -------
        bool
            Whether or not the Index is of the object dtype.

        See Also
        --------
        is_boolean : Check if the Index only consists of booleans.
        is_integer : Check if the Index only consists of integers.
        is_floating : Check if the Index is a floating type.
        is_numeric : Check if the Index only consists of numeric data.
        is_categorical : Check if the Index holds categorical data.
        is_interval : Check if the Index holds Interval objects.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index(["Apple", "Mango", "Watermelon"])
        >>> idx.is_object()
        True

        >>> idx = pd.Index(["Apple", "Mango", 2.0])
        >>> idx.is_object()
        True

        >>> idx = pd.Index(["Watermelon", "Orange", "Apple",
        ...                 "Watermelon"]).astype("category")
        >>> idx.is_object()
        False

        >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0])
        >>> idx.is_object()
        False
        )rK   r   r   r   r   r   r  
  s   
'zIndex.is_objectc                 C  r^  )a  
        Check if the Index holds categorical data.

        Returns
        -------
        bool
            True if the Index is categorical.

        See Also
        --------
        CategoricalIndex : Index for categorical data.
        is_boolean : Check if the Index only consists of booleans.
        is_integer : Check if the Index only consists of integers.
        is_floating : Check if the Index is a floating type.
        is_numeric : Check if the Index only consists of numeric data.
        is_object : Check if the Index is of the object dtype.
        is_interval : Check if the Index holds Interval objects.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index(["Watermelon", "Orange", "Apple",
        ...                 "Watermelon"]).astype("category")
        >>> idx.is_categorical()
        True

        >>> idx = pd.Index([1, 3, 5, 7])
        >>> idx.is_categorical()
        False

        >>> s = pd.Series(["Peter", "Victor", "Elisabeth", "Mar"])
        >>> s
        0        Peter
        1       Victor
        2    Elisabeth
        3          Mar
        dtype: object
        >>> s.index.is_categorical()
        False
        )r  r`  r   r   r   r   is_categorical?
  rf  zIndex.is_categoricalc                 C  r^  )a  
        Check if the Index holds Interval objects.

        Returns
        -------
        bool
            Whether or not the Index holds Interval objects.

        See Also
        --------
        IntervalIndex : Index for Interval objects.
        is_boolean : Check if the Index only consists of booleans.
        is_integer : Check if the Index only consists of integers.
        is_floating : Check if the Index is a floating type.
        is_numeric : Check if the Index only consists of numeric data.
        is_object : Check if the Index is of the object dtype.
        is_categorical : Check if the Index holds categorical data.
        is_mixed : Check if the Index holds data with mixed data types.

        Examples
        --------
        >>> idx = pd.Index([pd.Interval(left=0, right=5),
        ...                 pd.Interval(left=5, right=10)])
        >>> idx.is_interval()
        True

        >>> idx = pd.Index([1, 3, 5, 7])
        >>> idx.is_interval()
        False
        )intervalr`  r   r   r   r   is_intervalk
  s   
 zIndex.is_intervalc                 C  s   t jdtt d | jdv S )a  
        Check if the Index holds data with mixed data types.

        Returns
        -------
        bool
            Whether or not the Index holds data with mixed data types.

        See Also
        --------
        is_boolean : Check if the Index only consists of booleans.
        is_integer : Check if the Index only consists of integers.
        is_floating : Check if the Index is a floating type.
        is_numeric : Check if the Index only consists of numeric data.
        is_object : Check if the Index is of the object dtype.
        is_categorical : Check if the Index holds categorical data.
        is_interval : Check if the Index holds Interval objects.

        Examples
        --------
        >>> idx = pd.Index(['a', np.nan, 'b'])
        >>> idx.is_mixed()
        True

        >>> idx = pd.Index([1.0, 2.0, 3.0, 5.0])
        >>> idx.is_mixed()
        False
        zqIndex.is_mixed is deprecated and will be removed in a future version. Check index.inferred_type directly instead.r   )r   r  r  r  r0   r  r   r   r   r   is_mixed
  s   
zIndex.is_mixedc                 C  r^  )z6
        Whether the type is an integer type.
        )rc  r   r`  r   r   r   r   holds_integer
     
zIndex.holds_integerc                 C  s   t j| jddS )zG
        Return a string of the type inferred from the values.
        Fskipna)r   infer_dtyper#  r   r   r   r   r  
  s   zIndex.inferred_typec                 C  s4   t | jrdS | jtkrdS | jrdS tt| jS )H
        Whether or not the index values only consist of dates.
        TF)rP   r   r(  rS  r   r<   r#  r   r   r   r   _is_all_dates
  s   

zIndex._is_all_datesc                 C  rS  )rr  ziIndex.is_all_dates is deprecated, will be removed in a future version. check index.inferred_type instead.r   )r  r  r  r0   rs  r   r   r   r   is_all_dates
  s   zIndex.is_all_datesc                 C  s
   t | tS )zI
        Cached check equivalent to isinstance(self, MultiIndex)
        )r	  r\   r   r   r   r   rS  
  s   
zIndex._is_multic                 C  s    | j | jd}tt| |fd fS )N)r   r   )r   r   r   r  )r   r   r   r   r   
__reduce__
  s   zIndex.__reduce__c                 C  s,   | j }t|tj r|jdv rtS tjS |jS )z-The expected NA value to use with this index.r>  r=  )r   r	  r   r$  r   rK  na_valuer  r   r   r   r  
  s   
zIndex._na_valuenpt.NDArray[np.bool_]c                 C  s0   | j rt| S tjt| tjd}|d |S )z.
        Return if each value is NaN.
        r  F)r  rd   r   emptyrd  rF  fill)r   rO  r   r   r   _isnan
  s
   
zIndex._isnanc                 C  s   | j r
t| j S dS )zc
        Return True if there are any NaNs.

        Enables various performance speedups.
        F)r  r   r{  r  r   r   r   r   hasnans	  s   zIndex.hasnansc                 C  r  )a  
        Detect missing values.

        Return a boolean same-sized object indicating if the values are NA.
        NA values, such as ``None``, :attr:`numpy.NaN` or :attr:`pd.NaT`, get
        mapped to ``True`` values.
        Everything else get mapped to ``False`` values. Characters such as
        empty strings `''` or :attr:`numpy.inf` are not considered NA values
        (unless you set ``pandas.options.mode.use_inf_as_na = True``).

        Returns
        -------
        numpy.ndarray[bool]
            A boolean array of whether my values are NA.

        See Also
        --------
        Index.notna : Boolean inverse of isna.
        Index.dropna : Omit entries with missing values.
        isna : Top-level isna.
        Series.isna : Detect missing values in Series object.

        Examples
        --------
        Show which entries in a pandas.Index are NA. The result is an
        array.

        >>> idx = pd.Index([5.2, 6.0, np.NaN])
        >>> idx
        Float64Index([5.2, 6.0, nan], dtype='float64')
        >>> idx.isna()
        array([False, False,  True])

        Empty strings are not considered NA values. None is considered an NA
        value.

        >>> idx = pd.Index(['black', '', 'red', None])
        >>> idx
        Index(['black', '', 'red', None], dtype='object')
        >>> idx.isna()
        array([False, False, False,  True])

        For datetimes, `NaT` (Not a Time) is considered as an NA value.

        >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'),
        ...                         pd.Timestamp(''), None, pd.NaT])
        >>> idx
        DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'],
                      dtype='datetime64[ns]', freq=None)
        >>> idx.isna()
        array([False,  True,  True,  True])
        )r{  r   r   r   r   rd     s   6z
Index.isnac                 C  s
   |    S )a  
        Detect existing (non-missing) values.

        Return a boolean same-sized object indicating if the values are not NA.
        Non-missing values get mapped to ``True``. Characters such as empty
        strings ``''`` or :attr:`numpy.inf` are not considered NA values
        (unless you set ``pandas.options.mode.use_inf_as_na = True``).
        NA values, such as None or :attr:`numpy.NaN`, get mapped to ``False``
        values.

        Returns
        -------
        numpy.ndarray[bool]
            Boolean array to indicate which entries are not NA.

        See Also
        --------
        Index.notnull : Alias of notna.
        Index.isna: Inverse of notna.
        notna : Top-level notna.

        Examples
        --------
        Show which entries in an Index are not NA. The result is an
        array.

        >>> idx = pd.Index([5.2, 6.0, np.NaN])
        >>> idx
        Float64Index([5.2, 6.0, nan], dtype='float64')
        >>> idx.notna()
        array([ True,  True, False])

        Empty strings are not considered NA values. None is considered a NA
        value.

        >>> idx = pd.Index(['black', '', 'red', None])
        >>> idx
        Index(['black', '', 'red', None], dtype='object')
        >>> idx.notna()
        array([ True,  True,  True, False])
        )rd   r   r   r   r   notnaO  s   
+zIndex.notnac                 C  sR   |  |}| jr%| | j|}|du rtj|| jdS tt| j	 d| 
 S )a  
        Fill NA/NaN values with the specified value.

        Parameters
        ----------
        value : scalar
            Scalar value to use to fill holes (e.g. 0).
            This value cannot be a list-likes.
        downcast : dict, default is None
            A dict of item->dtype of what to downcast if possible,
            or the string 'infer' which will try to downcast to an appropriate
            equal type (e.g. float64 to int64 if possible).

        Returns
        -------
        Index

        See Also
        --------
        DataFrame.fillna : Fill NaN values of a DataFrame.
        Series.fillna : Fill NaN Values of a Series.
        Nr   zF.fillna does not support 'downcast' argument values other than 'None'.)_require_scalarr|  rJ  r{  r   rV  r   rJ  r  r  rt  )r   r  downcastr4  r   r   r   fillna~  s   
zIndex.fillnar  r   c                 C  sF   |dvrt d| | jr| j| j  }t| j|| jdS |  S )a  
        Return Index without NA/NaN values.

        Parameters
        ----------
        how : {'any', 'all'}, default 'any'
            If the Index is a MultiIndex, drop the value when any or all levels
            are NaN.

        Returns
        -------
        Index
        )r  r.  zinvalid how option: r   )r9  r|  r#  r{  r  r!  r   rt  )r   r   r  r   r   r   rN    s   zIndex.dropnar   c                   s4   |dur	|  | | jr|  S t  }| |S )a6  
        Return unique values in the index.

        Unique values are returned in order of appearance, this does NOT sort.

        Parameters
        ----------
        level : int or hashable, optional
            Only return values from specified level (for MultiIndex).
            If int, gets the level by integer position, else by level name.

        Returns
        -------
        Index

        See Also
        --------
        unique : Numpy array of unique values in that column.
        Series.unique : Return unique values of Series object.
        N)r9  rY  rt  superr   rr  )r   r   r4  	__class__r   r   r     s   


zIndex.uniquer_  ra  str_t | boolc                   s   | j r|  S t j|dS )a  
        Return Index with duplicate values removed.

        Parameters
        ----------
        keep : {'first', 'last', ``False``}, default 'first'
            - 'first' : Drop duplicates except for the first occurrence.
            - 'last' : Drop duplicates except for the last occurrence.
            - ``False`` : Drop all duplicates.

        Returns
        -------
        deduplicated : Index

        See Also
        --------
        Series.drop_duplicates : Equivalent method on Series.
        DataFrame.drop_duplicates : Equivalent method on DataFrame.
        Index.duplicated : Related method on Index, indicating duplicate
            Index values.

        Examples
        --------
        Generate an pandas.Index with duplicate values.

        >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'])

        The `keep` parameter controls  which duplicate values are removed.
        The value 'first' keeps the first occurrence for each
        set of duplicated entries. The default value of keep is 'first'.

        >>> idx.drop_duplicates(keep='first')
        Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object')

        The value 'last' keeps the last occurrence for each set of duplicated
        entries.

        >>> idx.drop_duplicates(keep='last')
        Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object')

        The value ``False`` discards all sets of duplicated entries.

        >>> idx.drop_duplicates(keep=False)
        Index(['cow', 'beetle', 'hippo'], dtype='object')
        r`  )rY  rt  r  drop_duplicatesr   ra  r  r   r   r    s   /zIndex.drop_duplicatesLiteral['first', 'last', False]c                 C  s$   | j rtjt| tdS | j|dS )a   
        Indicate duplicate index values.

        Duplicated values are indicated as ``True`` values in the resulting
        array. Either all duplicates, all except the first, or all except the
        last occurrence of duplicates can be indicated.

        Parameters
        ----------
        keep : {'first', 'last', False}, default 'first'
            The value or values in a set of duplicates to mark as missing.

            - 'first' : Mark duplicates as ``True`` except for the first
              occurrence.
            - 'last' : Mark duplicates as ``True`` except for the last
              occurrence.
            - ``False`` : Mark all duplicates as ``True``.

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

        See Also
        --------
        Series.duplicated : Equivalent method on pandas.Series.
        DataFrame.duplicated : Equivalent method on pandas.DataFrame.
        Index.drop_duplicates : Remove duplicate values from Index.

        Examples
        --------
        By default, for each set of duplicated values, the first occurrence is
        set to False and all others to True:

        >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama'])
        >>> idx.duplicated()
        array([False, False,  True, False,  True])

        which is equivalent to

        >>> idx.duplicated(keep='first')
        array([False, False,  True, False,  True])

        By using 'last', the last occurrence of each set of duplicated values
        is set on False and all others on True:

        >>> idx.duplicated(keep='last')
        array([ True, False,  True, False, False])

        By setting keep on ``False``, all duplicates are True:

        >>> idx.duplicated(keep=False)
        array([ True, False,  True, False,  True])
        r  r`  )rY  r   zerosrd  r   _duplicatedr  r   r   r   r     s   8zIndex.duplicatedc                 C  s   | | S r   r   rv  r   r   r   __iadd__N  rW  zIndex.__iadd__c                 C     t jdtt d | |S )NzIndex.__and__ operating as a set operation is deprecated, in the future this will be a logical operation matching Series.__and__.  Use index.intersection(other) instead.r   )r  r  r  r0   intersectionrv  r   r   r   __and__R     
zIndex.__and__c                 C  r  )NzIndex.__or__ operating as a set operation is deprecated, in the future this will be a logical operation matching Series.__or__.  Use index.union(other) instead.r   )r  r  r  r0   unionrv  r   r   r   __or__]  r  zIndex.__or__c                 C  r  )NzIndex.__xor__ operating as a set operation is deprecated, in the future this will be a logical operation matching Series.__xor__.  Use index.symmetric_difference(other) instead.r   )r  r  r  r0   symmetric_differencerv  r   r   r   __xor__h  r  zIndex.__xor__r   c                 C  s   t dt| j d)NzThe truth value of a zC is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().)r9  r  r  r   r   r   r   __nonzero__s  s   zIndex.__nonzero__c                 C  s"   t | |}| j|ur| |S | S )z
        If the result of a set operation will be self,
        return self, unless the name changes, in which
        case make a shallow copy of self.
        )rx   r   r3  )r   r   r   r   r   r   _get_reconciled_name_object  s   


z!Index._get_reconciled_name_objectc                 C  s   |dvrt d| dd S )NNFz;The 'sort' keyword only takes the values of None or False; z was passed.r9  )r   r   r   r   r   _validate_sort_keyword  s   zIndex._validate_sort_keywordsetopc                 C  s\   t | tr&t |tr(| jdur*|jdur,tjd| d| dtt d dS dS dS dS dS )zt
        Deprecate setop behavior between timezone-aware DatetimeIndexes with
        mismatched timezones.
        NzIn a future version, the z of DatetimeIndex objects with mismatched timezones will cast both to UTC instead of object dtype. To retain the old behavior, use `index.astype(object).z(other)`r   )r	  r[   r   r  r  r  r0   )r   r   r  r   r   r   _deprecate_dti_setop  s    	
zIndex._deprecate_dti_setopc                 C  s   |  | | | | |\}}t| j|jsMt| tr-tt|s-t	|dkr-t
d| |d | |}| j|dd}|j|dd}|j||dS t	|rV| |r[| |S t	| sd|| S | j||d}| ||S )a  
        Form the union of two Index objects.

        If the Index objects are incompatible, both Index objects will be
        cast to dtype('object') first.

            .. versionchanged:: 0.25.0

        Parameters
        ----------
        other : Index or array-like
        sort : bool or None, default None
            Whether to sort the resulting Index.

            * None : Sort the result, except when

              1. `self` and `other` are equal.
              2. `self` or `other` has length 0.
              3. Some values in `self` or `other` cannot be compared.
                 A RuntimeWarning is issued in this case.

            * False : do not sort the result.

        Returns
        -------
        union : Index

        Examples
        --------
        Union matching dtypes

        >>> idx1 = pd.Index([1, 2, 3, 4])
        >>> idx2 = pd.Index([3, 4, 5, 6])
        >>> idx1.union(idx2)
        Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')

        Union mismatched dtypes

        >>> idx1 = pd.Index(['a', 'b', 'c', 'd'])
        >>> idx2 = pd.Index([1, 2, 3, 4])
        >>> idx1.union(idx2)
        Index(['a', 'b', 'c', 'd', 1, 2, 3, 4], dtype='object')

        MultiIndex case

        >>> idx1 = pd.MultiIndex.from_arrays(
        ...     [[1, 1, 2, 2], ["Red", "Blue", "Red", "Blue"]]
        ... )
        >>> idx1
        MultiIndex([(1,  'Red'),
            (1, 'Blue'),
            (2,  'Red'),
            (2, 'Blue')],
           )
        >>> idx2 = pd.MultiIndex.from_arrays(
        ...     [[3, 3, 2, 2], ["Red", "Green", "Red", "Green"]]
        ... )
        >>> idx2
        MultiIndex([(3,   'Red'),
            (3, 'Green'),
            (2,   'Red'),
            (2, 'Green')],
           )
        >>> idx1.union(idx2)
        MultiIndex([(1,  'Blue'),
            (1,   'Red'),
            (2,  'Blue'),
            (2, 'Green'),
            (2,   'Red'),
            (3, 'Green'),
            (3,   'Red')],
           )
        >>> idx1.union(idx2, sort=False)
        MultiIndex([(1,   'Red'),
            (1,  'Blue'),
            (2,   'Red'),
            (2,  'Blue'),
            (3,   'Red'),
            (3, 'Green'),
            (2, 'Green')],
           )
        r   zjCan only union MultiIndex with MultiIndex or Index of tuples, try mi.to_flat_index().union(other) instead.r  Fr   r   )r  _assert_can_do_setop_convert_can_do_setopr@   r   r	  r\   rK   unpack_nested_dtyperd  rJ  r  _find_common_type_compatr  r  equalsr  _union_wrap_setop_result)r   r   r   result_namer   r   rightr4  r   r   r   r    s0   
T





zIndex.unionc           
   	     s$  | j }|j }|du rH| jrH|jrH| jr|jsH| jrHz| |d W S  ttfyG   t|}t| |	 fdd|D  t
j|td Y S w |jsVt||}t||S | jrg| |}|dk d }n
t| |d }t|dkr||}	t||	f}n|}| jr|jst||}|S )a  
        Specific union logic should go here. In subclasses, union behavior
        should be overwritten here rather than in `self.union`.

        Parameters
        ----------
        other : Index or array-like
        sort : False or None, default False
            Whether to sort the resulting index.

            * False : do not sort the result.
            * None : sort the result, except when `self` and `other` are equal
              or when the values cannot be compared.

        Returns
        -------
        Index
        Nr   c                   s   g | ]}| vr|qS r   r   r  	value_setr   r   r  G  r  z Index._union.<locals>.<listcomp>r  r  r   )r#  rT  r]  _can_use_libjoinr   r   r   r-  r   extendr   r  r   rY  r   union_with_duplicates_maybe_try_sort_index_as_uniqueget_indexernonzerounique1dget_indexer_non_uniquerd  r  rS   )
r   r   r   lvalsrvals
value_listr4  indexerrf   
other_diffr   r  r   r    sH   





zIndex._unionc                 C  s>   t | |}t|tr|j|kr||}|S | j||d}|S Nr   )rx   r	  r   r   r3  rr  )r   r   r4  r   r   r   r   r  d  s   



zIndex._wrap_setop_resultc                 C  s|  |  | | | | |\}}t| j|js| |d | |r2| jr-|  	|S | 	|S t
| dks>t
|dkrw| jsD|jrM| dd |S | |}t| j|rpt
| dkrg| dd |S |dd |S tg ||dS | |st| tr| dd |S tg |dS t| j|js| |}| j|dd}|j|dd}|j||dS | j||d}| ||S )	a  
        Form the intersection of two Index objects.

        This returns a new Index with elements common to the index and `other`.

        Parameters
        ----------
        other : Index or array-like
        sort : False or None, default False
            Whether to sort the resulting index.

            * False : do not sort the result.
            * None : sort the result, except when `self` and `other` are equal
              or when the values cannot be compared.

        Returns
        -------
        intersection : Index

        Examples
        --------
        >>> idx1 = pd.Index([1, 2, 3, 4])
        >>> idx2 = pd.Index([3, 4, 5, 6])
        >>> idx1.intersection(idx2)
        Int64Index([3, 4], dtype='int64')
        r  r   N)r   r   r   Fr   r  )r  r  r  r@   r   r  r  r]  r   r  rd  rS  r3  r  r   _should_comparer	  r\   r  r  _intersection_wrap_intersection_result)r   r   r   r  r   thisr4  r   r   r   r  n  s:   







zIndex.intersectionc                 C  sf   | j r%|j r%| jr%z	| |d }W n	 ty   Y n
w t|}t|S | j||d}t||}|S )zL
        intersection specialized to the case with matching dtypes.
        r   r  )	rT  r  r   r   r   r  rs   _intersection_via_get_indexerr  )r   r   r   r4  resr  r   r   r   r    s    

zIndex._intersectionc                 C     |  ||S r   r  r   r   r4  r   r   r   r       zIndex._wrap_intersection_resultr   c           	      C  sV   |   }|  }||}|dk}|| d }|du r#t|}||j}|S )z
        Find the intersection of two Indexes using get_indexer.

        Returns
        -------
        np.ndarray or ExtensionArray
            The returned array will be unique.
        r  r   F)r   get_indexer_forr  r  r   r   r#  )	r   r   r   left_uniqueright_uniquer  r	  takerr4  r   r   r   r    s   


z#Index._intersection_via_get_indexerc                 C  s   |  | | | | |\}}| |r| dd |S t|dkr*| |S | |s4| |S | j||d}| ||S )a  
        Return a new Index with elements of index not in `other`.

        This is the set difference of two Index objects.

        Parameters
        ----------
        other : Index or array-like
        sort : False or None, default None
            Whether to sort the resulting index. By default, the
            values are attempted to be sorted, but any TypeError from
            incomparable elements is caught by pandas.

            * None : Attempt to sort the result, but catch any TypeErrors
              from comparing incomparable elements.
            * False : Do not sort the result.

        Returns
        -------
        difference : Index

        Examples
        --------
        >>> idx1 = pd.Index([2, 1, 3, 4])
        >>> idx2 = pd.Index([3, 4, 5, 6])
        >>> idx1.difference(idx2)
        Int64Index([1, 2], dtype='int64')
        >>> idx1.difference(idx2, sort=False)
        Int64Index([2, 1], dtype='int64')
        Nr   r  )	r  r  r  r  r3  rd  r  _difference_wrap_difference_result)r   r   r   r  r4  r   r   r   
difference  s   
 




zIndex.differencec                 C  sZ   |   }||}||dk d }tjt|j|dd}|j|}t	||}|S )Nr  r   Tassume_unique)
r   r  r  r  r   	setdiff1dre  sizer#  r  )r   r   r   r  r  
label_diffthe_diffr   r   r   r  *  s   

zIndex._differencec                 C  r  r   r  r  r   r   r   r  8  r  zIndex._wrap_difference_resultc                 C  s  |  | | | | |\}}|du r|}t| j|js$| |d | |s3| j||d|S t| j|jsW| 	|}| j
|dd}|j
|dd}|j||d|S |  }| }||}||dk d }	tjt|j|	dd	}
|j|
}|dk d }|j|}t||g}t||}t|||jd
}| jrtd| } t|dkrt| dd t| jD dd t| jD |jdS t| j||jdS |S )ae  
        Compute the symmetric difference of two Index objects.

        Parameters
        ----------
        other : Index or array-like
        result_name : str
        sort : False or None, default None
            Whether to sort the resulting index. By default, the
            values are attempted to be sorted, but any TypeError from
            incomparable elements is caught by pandas.

            * None : Attempt to sort the result, but catch any TypeErrors
              from comparing incomparable elements.
            * False : Do not sort the result.

        Returns
        -------
        symmetric_difference : Index

        Notes
        -----
        ``symmetric_difference`` contains elements that appear in either
        ``idx1`` or ``idx2`` but not both. Equivalent to the Index created by
        ``idx1.difference(idx2) | idx2.difference(idx1)`` with duplicates
        dropped.

        Examples
        --------
        >>> idx1 = pd.Index([1, 2, 3, 4])
        >>> idx2 = pd.Index([2, 3, 4, 5])
        >>> idx1.symmetric_difference(idx2)
        Int64Index([1, 5], dtype='int64')
        Nr  r  Fr   r  r   Tr  r   r   r   c                 S     g | ]}g qS r   r   r  _r   r   r   r        z.Index.symmetric_difference.<locals>.<listcomp>c                 S  r  r   r   r  r   r   r   r    r  )rI  r   r  r  ) r  r  r  r@   r   r  r  r  r3  r  r  r  r   r  r  r  r   r  re  r  r#  rS   r  r   rS  r   rd  r  r  rh  r   r0  )r   r   r  r   result_name_updater   r  thatr  common_indexerleft_indexer	left_diffright_indexer
right_diffr  r4  r   r   r   r  <  sJ   
#





zIndex.symmetric_differencec                 C  s   t |stddS )Nz!Input must be Index or array-likeT)rI   r   rv  r   r   r   r    s   zIndex._assert_can_do_setoptuple[Index, Hashable]c                 C  sV   t |ts"t|drt|| j|jd}nt|| jd}| j}||fS t| |}||fS )Nr   r  r   )r	  r   r,  r   r   rx   )r   r   r  r   r   r   r    s   


zIndex._convert_can_do_setopc              
   C  s  |du r6|durt d| |}z| j|W S  ty) } zt||d}~w ty5   | |  w tjdt	| j
 dtt d t|rUt|rU| jsUt||durb| |t|}| j|g||d}|jdksu|jdkrytd| }|d	krt||S )
a  
        Get integer location, slice or boolean mask for requested label.

        Parameters
        ----------
        key : label
        method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional
            * default: exact matches only.
            * pad / ffill: find the PREVIOUS index value if no exact match.
            * backfill / bfill: use NEXT index value if no exact match
            * nearest: use the NEAREST index value if no exact match. Tied
              distances are broken by preferring the larger index value.

            .. deprecated:: 1.4
                Use index.get_indexer([item], method=...) instead.

        tolerance : int or float, optional
            Maximum distance from index value for inexact matches. The value of
            the index at the matching location must satisfy the equation
            ``abs(index[loc] - key) <= tolerance``.

        Returns
        -------
        loc : int if unique index, slice if monotonic index, else mask

        Examples
        --------
        >>> unique_index = pd.Index(list('abc'))
        >>> unique_index.get_loc('b')
        1

        >>> monotonic_index = pd.Index(list('abbc'))
        >>> monotonic_index.get_loc('b')
        slice(1, 3, None)

        >>> non_monotonic_index = pd.Index(list('abcb'))
        >>> non_monotonic_index.get_loc('b')
        array([False,  True, False,  True])
        NzGtolerance argument only valid if using pad, backfill or nearest lookupszPassing method to zm.get_loc is deprecated and will raise in a future version. Use index.get_indexer([item], method=...) instead.r   )r  	tolerancer   z$get_loc requires scalar valued inputr  )r9  _maybe_cast_indexerrx  get_locr7  r   _check_indexing_errorr  r  r  r  r  r0   rL   rd   r|  _convert_tolerancer   r%  r  r8  r  item)r   keyr  r  
casted_keyr  r  locr   r   r   r    s>   (


zIndex.get_locaW  
        Compute indexer and mask for new index given the current index.

        The indexer should be then used as an input to ndarray.take to align the
        current data to the new index.

        Parameters
        ----------
        target : %(target_klass)s
        method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional
            * default: exact matches only.
            * pad / ffill: find the PREVIOUS index value if no exact match.
            * backfill / bfill: use NEXT index value if no exact match
            * nearest: use the NEAREST index value if no exact match. Tied
              distances are broken by preferring the larger index value.
        limit : int, optional
            Maximum number of consecutive labels in ``target`` to match for
            inexact matches.
        tolerance : optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.

            Tolerance may be a scalar value, which applies the same tolerance
            to all values, or list-like, which applies variable tolerance per
            element. List-like includes list, tuple, array, Series, and must be
            the same size as the index and its dtype must exactly match the
            index's type.

        Returns
        -------
        indexer : np.ndarray[np.intp]
            Integers from 0 to n - 1 indicating that the index at these
            positions matches the corresponding target values. Missing values
            in the target are marked by -1.
        %(raises_section)s
        Notes
        -----
        Returns -1 for unmatched values, for further explanation see the
        example below.

        Examples
        --------
        >>> index = pd.Index(['c', 'a', 'b'])
        >>> index.get_indexer(['a', 'b', 'x'])
        array([ 1,  2, -1])

        Notice that the return value is an array of locations in ``index``
        and ``x`` is marked by -1, as it is not in ``index``.
        r  str_t | Nonelimit
int | Nonec                 C  s  t |}|}| |}| ||| | jst| jt|dkr)tj	g tj
dS | |s;| |s;| j||ddS t| jrqt| j|jsIJ | j|j}| jro|jrot|}| tj}| }	|||< d||	| @ < |S t|jr| |j}
tj|
|jdd}| js| jr|jr| tj}| }	|||	< t|S | |\}}|| us||ur|j||||dS t| j|jr| |rtjt|tj
dS t| j|jst | js| !|}| j"|dd	}|j"|dd	}|j#||||dS | #||||S )
Nr   r  Tr  r   r  )r  r  r  r  Fr   )$rf   clean_reindex_fill_method_maybe_cast_listlike_indexer_check_indexing_methodr  r+   _requires_unique_msgrd  r   r  intpr  _should_partial_index_get_indexer_non_comparabler?   r   r@   rx  r  r   r|  rd   r  rK  r  r   take_ndrS  r=   _maybe_promoter  re  rG   r  r  _get_indexer)r   targetr  r  r  orig_targetr  target_nansr  r	  categories_indexerpselfptargetr   r  r   r   r   r  1  sZ   
	




zIndex.get_indexerr  c                 C  s   |d ur
|  ||}|dv r| ||||}t|S |dkr)| |||}t|S |jr8| jr8| j}||}n| }| j|}t|S )N)padbackfillnearest)	r  _get_fill_indexer_get_nearest_indexerrS  rx  _extract_level_codesr   r  r=   )r   r  r  r  r  r  engine
tgt_valuesr   r   r   r    s    zIndex._get_indexerc                 C  s    t | jrt |jrdS dS dS )z>
        Should we attempt partial-matching indexing?
        FT)rG   r   r   r  r   r   r   r    s
   

zIndex._should_partial_indexc                 C  s   |dvrt d| jr#|dkrtd|dks|dkr#|dur#tdt| js-t| jr>|dur>td	| d
t| j |du rR|durJt d|durTt ddS dS )zY
        Raise if we have a get_indexer `method` that is not supported or valid.
        )Nbfillr  r  ffillr  zInvalid fill methodr  zJmethod='nearest' not implemented yet for MultiIndex; see GitHub issue 9365r  r  Nz,tolerance not implemented yet for MultiIndexzmethod z not yet implemented for zJtolerance argument only valid if doing pad, backfill or nearest reindexingzFlimit argument only valid if doing pad, backfill or nearest reindexing)r9  rS  rJ  rG   r   r?   r  r  )r   r  r  r  r   r   r   r    s8   
zIndex._check_indexing_methodnp.ndarray | Indexc                 C  s,   t |}|j|jkr|jdkrtd|S )Nr   z5list-like tolerance size must match target index size)r   r%  r  r9  )r   r  r  r   r   r   r    s   
zIndex._convert_tolerancec           	      C  s   | j r| j}|j|j| j||dS | jrC|jrC| }|  }t|tjr+t|tjs-t	|dkr:t
j|||d}nt
j|||d}n| |||}|d urYt| rY| |||}|S )N)r  rO  r  r  r  r  )rS  rx  get_indexer_with_fillr#  rT  r   r	  r   r   rJ  libalgosr  r  _get_fill_indexer_searchsortedrd  _filter_indexer_tolerance)	r   r  r  r  r  r  r  
own_valuesr  r   r   r   r    s&   zIndex._get_fill_indexerc                 C  s   |durt dt| d|dkrdnd}| |}|dk}| || |||< |dkr7||  d8  < |S d||t| k< |S )	z
        Fallback pad/backfill get_indexer that works for monotonic decreasing
        indexes and non-monotonic targets.
        Nzlimit argument for z; method only well-defined if index and target are monotonicr  r   r  r  r   )r9  r   r  _searchsorted_monotonicrd  )r   r  r  r  sider  nonexactr   r   r   r    s   
z$Index._get_fill_indexer_searchsortedc           
      C  s   t | s
| |dS | j|d|d}| j|d|d}| ||}| ||}| jr,tjntj}t	||||dkB ||}	|durH| 
||	|}	|	S )z
        Get the indexer for the nearest index labels; requires an index with
        values that can be subtracted from each other (e.g., not strings or
        tuples).
        r  r  r  r  N)rd  r  r  _difference_compatrT  operatorltler   wherer  )
r   r  r  r  r  r  left_distancesright_distancesopr  r   r   r   r  -  s"   		zIndex._get_nearest_indexerr  c                 C  s   |  ||}t||k|dS )Nr  )r  r   r  )r   r  r  r  distancer   r   r   r  M  s   zIndex._filter_indexer_tolerancec                 C  sT   t | jtrtd| jj}td|jj}|| | }t|S | j| |j }t|S )Nr   )r	  r   rY   r   r   r  r#  abs)r   r  r  r  r  diffr   r   r   r  Y  s   zIndex._difference_compatr  slicec                 C  s4   |  d|jd |  d|jd |  d|jd dS )zz
        For positional indexing, a slice must have either int or None
        for each of start, stop, and step.
        
positionalilocN)_validate_indexerr   stopstepr   r  r   r   r   _validate_positional_slicen  s   z Index._validate_positional_slicer$  is_framec                 C  s  |dv sJ ||j |j|j}}}dd }||o"||o"||}| jp*t| j}	|o.|	}
|dkr	 |  r|r;nD|du rD|du rDn;t| trS| j	t
t| krSn,| jjdv rs| jrst| dkrs| d dkrs| d t| d	 krsn|svn	tjd
tt d |  s|r| d|j d | d|jd | d|jd |S |
rz|dur| | |dur| | d}
W n	 ty   Y nw t|r|}|S |
r|dkrtjdtt d |}|S | |||}|S )a  
        Convert a slice indexer.

        By definition, these are labels unless 'iloc' is passed in.
        Floats are not allowed as the start, step, or stop of the slice.

        Parameters
        ----------
        key : label of the slice bound
        kind : {'loc', 'getitem'}
        is_frame : bool, default False
            Whether this is a slice called on DataFrame.__getitem__
            as opposed to Series.__getitem__
        )r  getitemc                 S  s   | d u pt | S r   )rF   )r  r   r   r   is_int  s   z,Index._convert_slice_indexer.<locals>.is_intr   N)r  r  r   r  r   a  The behavior of `series[i:j]` with an integer-dtype index is deprecated. In a future version, this will be treated as *label-based* indexing, consistent with e.g. `series[i]` lookups. To retain the old behavior, use `series.iloc[i:j]`. To get the future behavior, use `series.loc[i:j]`.r   r  Fr  zSlicing a positional slice with .loc is not supported, and will raise TypeError in a future version.  Use .loc with labels or .iloc with positions instead.)r   r  r  _should_fallback_to_positionalrG   r   rF   r	  r^   _ranger  rd  r$  rY  r  r  r  r0   r  r  r7  r&  is_null_sliceslice_indexer)r   r  r$  r  r   r  r  r!  is_index_sliceints_are_positionalis_positionalr  r   r   r   _convert_slice_indexerx  s   


	


zIndex._convert_slice_indexerformr   c              
   C  s,   t d| dt| j d| dt|j S )z5
        Consistent invalid indexer message.
        z
cannot do z indexing on z with these indexers [z
] of type )r   r  r  )r   r*  r  r   r   r   _invalid_indexer  s   zIndex._invalid_indexerc                 C  s   | j st|rtddS dS )z
        Check if we are allowing reindexing with this particular indexer.

        Parameters
        ----------
        indexer : an integer ndarray

        Raises
        ------
        ValueError if its a duplicate axis
        z/cannot reindex on an axis with duplicate labelsN)r  rd  r9  )r   r  r   r   r   _validate_can_reindex  s   zIndex._validate_can_reindex)tuple[Index, npt.NDArray[np.intp] | None]c           
      C  s4  t |d }t|}t|ts+t|dkr+|dur"| jr"| j| }n| }|dd }nt|}|durTt| ts=t|trT|durEt	d| j
||d| j d\}}}	n;| |r\d}n3| jri| j||||d}n| jrptd|dusx|dur|td	| |\}}	| jstjd
tt d | |||}||fS )a  
        Create index with target's values.

        Parameters
        ----------
        target : an iterable
        method : {None, 'pad'/'ffill', 'backfill'/'bfill', 'nearest'}, optional
            * default: exact matches only.
            * pad / ffill: find the PREVIOUS index value if no exact match.
            * backfill / bfill: use NEXT index value if no exact match
            * nearest: use the NEAREST index value if no exact match. Tied
              distances are broken by preferring the larger index value.
        level : int, optional
            Level of multiindex.
        limit : int, optional
            Maximum number of consecutive labels in ``target`` to match for
            inexact matches.
        tolerance : int or float, optional
            Maximum distance between original and new labels for inexact
            matches. The values of the index at the matching locations must
            satisfy the equation ``abs(index[indexer] - target) <= tolerance``.

            Tolerance may be a scalar value, which applies the same tolerance
            to all values, or list-like, which applies variable tolerance per
            element. List-like includes list, tuple, array, Series, and must be
            the same size as the index and its dtype must exactly match the
            index's type.

        Returns
        -------
        new_index : pd.Index
            Resulting index.
        indexer : np.ndarray[np.intp] or None
            Indices of output values in original index.

        Raises
        ------
        TypeError
            If ``method`` passed along with ``level``.
        ValueError
            If non-unique multi-index
        ValueError
            If non-unique index and ``method`` or ``limit`` passed.

        See Also
        --------
        Series.reindex : Conform Series to new index with optional filling logic.
        DataFrame.reindex : Conform DataFrame to new index with optional filling logic.

        Examples
        --------
        >>> idx = pd.Index(['car', 'bike', 'train', 'tractor'])
        >>> idx
        Index(['car', 'bike', 'train', 'tractor'], dtype='object')
        >>> idx.reindex(['car', 'bike'])
        (Index(['car', 'bike'], dtype='object'), array([0, 1]))
        r   r   Nz)Fill method not supported if level passedr  )r   
keep_orderr  z'cannot handle a non-unique multi-index!z8cannot reindex a non-unique index with a method or limitzTreindexing with a non-unique Index is deprecated and will raise in a future version.r   )r,  ensure_has_lenr	  r   rd  rS  rI  ensure_indexr\   r   _join_levelr  r  r  r9  r  rY  r  r  r  r0   _wrap_reindex_result)
r   r  r  r   r  r  preserve_namesr1  r  r  r   r   r   reindex	  sN   >
zIndex.reindexr3  c                 C  s   |  ||}|S r   )_maybe_preserve_names)r   r  r  r3  r   r   r   r2    s   zIndex._wrap_reindex_resultc                 C  s2   |r|j dkr|j| jkr|jdd}| j|_|S )Nr   Fr  )rh  r   r   )r   r  r3  r   r   r   r5    s   zIndex._maybe_preserve_names?tuple[Index, npt.NDArray[np.intp], npt.NDArray[np.intp] | None]c                 C  s  t |}t|dkr| dd tjg tjddfS | |\}}|dk}| || }d}t|rtjt|tjd}t|}||}||  }	| || j	}
|| }tj
t|ftd}|
||< |||	< t| sttjdtjd}n2|jrtjt|tjd}tt|
||< d||	< nd|| < tjt| |tjd}d|| < t| trt| j|| jd}ntj|| jd}|||fS )a  
        Create a new index with target's values (move/add/delete values as
        necessary) use with non-unique Index and a possibly non-unique target.

        Parameters
        ----------
        target : an iterable

        Returns
        -------
        new_index : pd.Index
            Resulting index.
        indexer : np.ndarray[np.intp]
            Indices of output values in original index.
        new_indexer : np.ndarray[np.intp] or None

        r   Nr  r  r  r   )r0  rd  r   r  r  r  r  re  r=   rO  ry  r   rY  r	  r\   r  r0  r  r   rV  r   )r   r  r  rf   check
new_labelsnew_indexerr  missing_labelsmissing_indexer
cur_labelscur_indexerr  r   r   r   _reindex_non_unique  s<   






zIndex._reindex_non_unique.r   r%   r   Literal[True]r   Ftuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]c                C     d S r   r   r   r   r   r   r   r   r   r   r   r        
z
Index.joinr   r   r   r   Literal[False]c                C  rA  r   r   rB  r   r   r   r     rC  NIndex | tuple[Index, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]c                C  rA  r   r   rB  r   r   r   r     rC  r   c                 C  s  t |}t| trt|tr| jdu |jdu A rtd| js;|js;| |\}}|| us1||ur;|j|||d|dS |du rS| jsE|jrS| j|jkrLn| j	||dS |dure| js]|jre| j
|||dS t|dkr|dv r|  }ttdt|}	|d|	fS |d	v r| }tg }
||
dfS t| dkr|d
v r| }ttdt|}
||
dfS |dv r|  }tg }	|d|	fS | j|jk rddd||}|j| ||dd\}}}||}}|||fS t| j|js| |}| j|dd}|j|dd}|j||ddS t| | js |js | j||dS | jr(|jsE| jr>|jr>t| js=| j||dS n=| j||dS | jr{|jr{| jr{t| trbtdd | j D s{t!| js{z| j||dW S  tyz   Y nw | "|||S )a@  
        Compute join_index and indexers to conform data structures to the new index.

        Parameters
        ----------
        other : Index
        how : {'left', 'right', 'inner', 'outer'}
        level : int or level name, default None
        return_indexers : bool, default False
        sort : bool, default False
            Sort the join keys lexicographically in the result Index. If False,
            the order of the join keys depends on the join type (how keyword).

        Returns
        -------
        join_index, (left_indexer, right_indexer)
        Nz0Cannot join tz-naive with tz-aware DatetimeIndexTrD  r   r   )r   outerr  )r  innercross)r  rH  )r   rI  rJ  r   r  r  r   )r   r   r   Fr   r   r   c                 s  s    | ]}t |V  qd S r   )r?   )r  r   r   r   r   r  m  r  zIndex.join.<locals>.<genexpr>)#r0  r	  r[   r   r   rS  r  r   r  _join_multir1  rd  rt  r   broadcast_tor  r  _join_precedencer1  r@   r   r  r  _validate_join_methodrY  _join_non_uniquerT  rG   _join_monotonicr  r\   r  dtypesr?   _join_via_get_indexer)r   r   r   r   r   r   r  potherr   rindexerlindexerr   r   r   r  r   r   r   r     s   
	








c                 C  s   |dkr| }n|dkr|}n|dkr| j |dd}n	|dkr#| |}|r)| }|| u r0d }n| |}||u r<d }n||}|||fS )Nr   r  rI  Fr  rH  )r  r  r>  r  )r   r   r   r   r   rW  rV  r   r   r   rT  {  s"   	



zIndex._join_via_get_indexerc                 C  s  ddl m} ddlm} ttj| j }ttj|j }|j}|j}t	|}	t	|}
|	|
@ }|s4t
dt| |rt||rt|	| |d}t|
| |d}t|| s]| }|| j}n
| |}||}|j||dd\}}}|| }|| |||||\}}}||||dd	}| }|||fS t|d }d}t| |r|| } }d}d
dd||}|j|}| j|||d}|r|d |d |d fS |S )Nr   r  ) restore_dropped_levels_multijoinz+cannot join with no overlapping index names)r  TrL  FrH  r   r  rK  rG  r  r   )r/  r   pandas.core.reshape.mergerX  r-  r&  not_noner  r   r   r9  r	  rC  rd  reorder_levelsrF  r   remove_unused_levelsr1  r1  )r   r   r   r   rX  self_names_listother_names_listself_names_orderother_names_order
self_namesother_namesoverlapldrop_namesrdrop_namesself_jnlevelsother_jnlevelsjoin_idxr   r   dropped_namesrI  r   r  multi_join_idxjl
flip_orderr   r4  r   r   r   rM    s^   






zIndex._join_multi8tuple[Index, npt.NDArray[np.intp], npt.NDArray[np.intp]]c           
      C  s   ddl m} | j|jksJ || jg|jg|dd\}}|dk}| j|}|j|}t|tjr:t||| n|	|| | 
||}	|	||fS )Nr   )get_join_indexersT)r   r   r  )rY  rn  r   r#  r  r	  r   r   rJ  _putmask_wrap_joined_index)
r   r   r   rn  left_idx	right_idxr	  
join_arrayr  r   r   r   r   rQ    s   

zIndex._join_non_uniquer.  Ktuple[MultiIndex, npt.NDArray[np.intp] | None, npt.NDArray[np.intp] | None]c                   s  ddl m} ddd}t| |rt||rtd	| |}}t| | }	|	r4||}}d
dd||}t||s;J ||}|j| }
|jsLtd|
j	||dd\}}}|du rx|sct
|dkrhd |}n||jd|d   |  }nt|}t|t
|
}|j| }||dk }||}t|j}|||< t|j}|||< |rtjt
|tjd ttj  |dk s͇fdd|D }   n`|dkrt
|dkrdn| }d| }t||\ } |d d   fdd|D }n2|dk }|sfdd|D }||d|d    fdd|D }|s. d    ||||jdd}|durE||j| }n|j| }|	rR|  } du rYdnt  |du rddnt|}| |fS )ai  
        The join method *only* affects the level of the resulting
        MultiIndex. Otherwise it just exactly aligns the Index data to the
        labels of the level in the MultiIndex.

        If ```keep_order == True```, the order of the data indexed by the
        MultiIndex will not be changed; otherwise, it will tie out
        with `other`.
        r   r  r   list[np.ndarray]r   r   c                 S  s   | d j dkrtjdtjdS t| dkrtt| d S | d dd | d dd k}| dd D ]}||dd |dd kO }q3tdg|dgf d }t	| d }t
|t|S )aj  
            Returns sorter for the inner most level while preserving the
            order of higher levels.

            Parameters
            ----------
            labels : list[np.ndarray]
                Each ndarray has signed integer dtype, not necessarily identical.

            Returns
            -------
            np.ndarray[np.intp]
            r   r  r   Nr  T)r  r   ry  r  rd  r{   r=   hstackr  r;   r   get_level_sorter)r   ticlabstartsr   r   r   _get_leaf_sorter  s    z+Index._join_level.<locals>._get_leaf_sorterz9Join on level between two MultiIndex objects is ambiguousr   r  rK  z8Index._join_level on non-unique index is not implementedTrL  Nr   r  r  c                      g | ]}|  qS r   r   r  ry  r	  r   r   r  p      z%Index._join_level.<locals>.<listcomp>c                   r|  r   r   r}  r  r   r   r  }  r  c                   r|  r   r   r}  r~  r   r   r    r  c                   r|  r   r   r}  r  r   r   r    r  FrH  )r   ru  r   r   )r/  r   r	  r   r1  r;  rI  rY  rJ  r   rd  r   r=   r   get_reverse_indexerr  r-  r   re  r  r   r   r.  maxr  groupsort_indexerr  r  )r   r   r   r   r.  r   r{  r   r  rl  	old_level	new_levelleft_lev_indexerright_lev_indexerr   rev_indexer	old_codesr  new_lev_codesrM  rL  max_new_levngroupscountsmask_allr  r   )r  r	  r   r1    s   













zIndex._join_levelc                 C  sh  |j | j ksJ | |r|dkr|n| }|d d fS | jrb|jrb|dkr.| }d }| |}nm|dkr<|}|| }d }n_|dkrO| |\}}}| ||}nL|dkra| |\}}}| ||}n9|dkro| |\}}}n&|dkr||| \}}}n|dkr| |\}}}n|dkr| |\}}}| ||}|d u rd nt|}|d u rd nt|}|||fS )Nr  r   rI  rH  )	r   r  rY  r   r   rp  r   r   r=   )r   r   r   	ret_indexr   r   r   rs  r   r   r   rR    s@   



zIndex._join_monotonicr   c                 C  s\   |j | j ksJ t| tr| j|jkr| jnd }| j||dS t| |}| jj||| j dS )Nr   r  )r   r	  r\   r  r"  rx   rV  )r   r   r   r   r   r   r   rp    s   

zIndex._wrap_joined_indexc                 C  s&   t | tu rt| jtjS t| j S )zJ
        Whether we can use the fastpaths implement in _libs.join
        )r  r   r	  r   r   rG   r   r   r   r   r    s   zIndex._can_use_libjoinc                 C  r  )a  
        Return an array representing the data in the Index.

        .. warning::

           We recommend using :attr:`Index.array` or
           :meth:`Index.to_numpy`, depending on whether you need
           a reference to the underlying data or a NumPy array.

        Returns
        -------
        array: numpy.ndarray or ExtensionArray

        See Also
        --------
        Index.array : Reference to the underlying data.
        Index.to_numpy : A NumPy array representing the underlying data.
        r   r   r   r   r   rO    s   zIndex.valuesrl   c                 C  s*   | j }t|tjrddlm} ||}|S )Nr   r   )r   r	  r   r   pandas.core.arrays.numpy_r   )r   r  r   r   r   r   r    s
   zIndex.arrayc                 C  r  )a
  
        The best array representation.

        This is an ndarray or ExtensionArray.

        ``_values`` are consistent between ``Series`` and ``Index``.

        It may differ from the public '.values' method.

        index             | values          | _values       |
        ----------------- | --------------- | ------------- |
        Index             | ndarray         | ndarray       |
        CategoricalIndex  | Categorical     | Categorical   |
        DatetimeIndex     | ndarray[M8ns]   | DatetimeArray |
        DatetimeIndex[tz] | ndarray[M8ns]   | DatetimeArray |
        PeriodIndex       | ndarray[object] | PeriodArray   |
        IntervalIndex     | IntervalArray   | IntervalArray |

        See Also
        --------
        values : Values
        r  r   r   r   r   r#    s   zIndex._valuesc                 C  s>   | j }t|tr|jS t| tu rt| j tr| j tS |S )zl
        Get the ndarray or ExtensionArray that we can pass to the IndexEngine
        constructor.
        )	r#  r	  rp   r  r  r   rl   r  r   )r   valsr   r   r   r   '  s   
zIndex._get_engine_targetr4  c                 C     |S )z{
        Cast the ndarray returned from one of the libjoin.foo_indexer functions
        back to type(self)._data.
        r   rs  r   r   r   r   5  r  zIndex._from_join_targetc                 C  s"   | j |d}|| jj|d7 }|S )Nr  )_memory_usagerx  sizeof)r   r  r4  r   r   r   memory_usage<  s   zIndex.memory_usagec                 C  s.   t | tr	tdtj|td}| | |S )a  
        Replace values where the condition is False.

        The replacement is taken from other.

        Parameters
        ----------
        cond : bool array-like with the same length as self
            Condition to select the values on.
        other : scalar, or array-like, default None
            Replacement if the condition is False.

        Returns
        -------
        pandas.Index
            A copy of self with values replaced from other
            where the condition is False.

        See Also
        --------
        Series.where : Same method for Series.
        DataFrame.where : Same method for DataFrame.

        Examples
        --------
        >>> idx = pd.Index(['car', 'bike', 'train', 'tractor'])
        >>> idx
        Index(['car', 'bike', 'train', 'tractor'], dtype='object')
        >>> idx.where(idx.isin(['car', 'train']), 'other')
        Index(['car', 'other', 'train', 'other'], dtype='object')
        z1.where is not supported for MultiIndex operationsr  )r	  r\   rJ  r   r%  r   rJ  )r   condr   r   r   r   r  D  s   
!zIndex.wherec                 C  s   t | j dt| dS )Nz5(...) must be called with a collection of some kind, z was passed)r   r  r   r   r   r   r   r   r+  m  s
   zIndex._scalar_data_errorc                 C     t d)NzMString dtype not supported, you may need to explicitly cast to a numeric typer   r  r   r   r   _string_data_errorw  s   zIndex._string_data_errorc              
   C  s\   | j }t|tj r$|jdvr$zt||W S  ty# } zt|d}~ww t| j|s,t|S )a  
        Check if the value can be inserted into our array without casting,
        and convert it to an appropriate native type if necessary.

        Raises
        ------
        TypeError
            If the value cannot be inserted into an array of this dtype.
        rv  N)	r   r	  r   r$  r:   r3   r   r4   r#  )r   r  r   r  r   r   r   _validate_fill_value  s   
zIndex._validate_fill_valuec                 C  s    t |stdt|j |S )z
        Check that this is a scalar value that we can use for setitem-like
        operations without changing dtype.
        z"'value' must be a scalar, passed: )rL   r   r  r  r  r   r   r   r~    s   zIndex._require_scalarc                 C  s   |   S )zH
        Return a boolean if we need a qualified .info display.
        )r  r   r   r   r   _is_memory_usage_qualified     z Index._is_memory_usage_qualifiedc                 C  s   t jdtt d || jkS )zN
        Whether the index type is compatible with the provided type.
        zOIndex.is_type_compatible is deprecated and will be removed in a future version.r   rk  )r   r$  r   r   r   is_type_compatible  s   
zIndex.is_type_compatibler   c              
   C  s0   t | z|| jv W S  tttfy   Y dS w )a  
        Return a boolean indicating whether the provided key is in the index.

        Parameters
        ----------
        key : label
            The key to check if it is present in the index.

        Returns
        -------
        bool
            Whether the key search is in the index.

        Raises
        ------
        TypeError
            If the key is not hashable.

        See Also
        --------
        Index.isin : Returns an ndarray of boolean dtype indicating whether the
            list-like key is in the index.

        Examples
        --------
        >>> idx = pd.Index([1, 2, 3, 4])
        >>> idx
        Int64Index([1, 2, 3, 4], dtype='int64')

        >>> 2 in idx
        True
        >>> 6 in idx
        False
        F)hashrx  OverflowErrorr   r9  r  r   r   r   __contains__  s   #zIndex.__contains__zClassVar[None]__hash__c                 C  r  )Nz)Index does not support mutable operationsr  )r   r  r  r   r   r   __setitem__  rW  zIndex.__setitem__c                 C  s   | j j}t|st|rtj|dd}||S t|tr*||}t| j	|| j
dS t|rFtt|ddr?|jtdd}ntj|td}||}|jd	kr]t| t|d
r[|jS |S | jj	|| j
dS )aA  
        Override numpy.ndarray's __getitem__ method to work as desired.

        This function adds lists and Series as valid boolean indexers
        (ndarrays only supports ndarray with dtype=bool).

        If resulting ndim != 1, plain ndarray is returned instead of
        corresponding `Index` subclass.

        T)
warn_floatr   r   NF)r   rw  r  r   r  )r   __getitem__rF   rC   r&  cast_scalar_indexerr	  r  r  r!  r   is_bool_indexerrB   r  r  r   r   r%  r8  rv   r,  r  r"  )r   r  r   r4  r   r   r   r    s$   



zIndex.__getitem__slobjc                 C  s   | j | }t| j|| jdS )zH
        Fastpath for __getitem__ when we know we have a slice.
        r   )r   r  r!  r   )r   r  r  r   r   r   _getitem_slice  s   
zIndex._getitem_slicec                 C  s&   |   st| js|  r|| v S dS )a]  
        Faster check for ``name in self`` when we know `name` is a Python
        identifier (e.g. in NDFrame.__getattr__, which hits this to support
        . key lookup). For indexes that can't hold identifiers (everything
        but object & categorical) we just return False.

        https://github.com/pandas-dev/pandas/issues/19764
        F)r  rN   r   rh  )r   r   r   r   r   $_can_hold_identifiers_and_holds_name  s   
z*Index._can_hold_identifiers_and_holds_nameIndex | Sequence[Index]c                 C  sx   | g}t |ttfr|t|7 }n|| |D ]}t |ts#tdqdd |D }t|dkr3dn| j}| ||S )z
        Append a collection of Index options together.

        Parameters
        ----------
        other : Index or list/tuple of indices

        Returns
        -------
        Index
        zall inputs must be Indexc                 S  s   h | ]}|j qS r   r   )r  objr   r   r   r  E      zIndex.append.<locals>.<setcomp>r   N)	r	  r-  r
  r  r   r   rd  r   _concat)r   r   	to_concatr  r  r   r   r   r   r  ,  s   

zIndex.appendr  list[Index]c                 C  sL   dd |D }t |}|jjdv }| jr|rt| j||dS tj||dS )z5
        Concatenate multiple Index objects.
        c                 S  s   g | ]}|j qS r   r  r  r   r   r   r  N  r  z!Index._concat.<locals>.<listcomp>r   r   )rS   r   r$  r   r  r!  r   rV  )r   r  r   to_concat_valsr4  rg  r   r   r   r  J  s   
zIndex._concatc              
   C  s   t | j|\}}|r|  S | jtkrt|| jr| j}z| |}W n) tt	t
fyL } zt| r4|| |}| |||W  Y d}~S d}~ww | j }t|tjrht|| |}t||| n||| | |S )a  
        Return a new Index of the values set with the mask.

        Returns
        -------
        Index

        See Also
        --------
        numpy.ndarray.putmask : Changes elements of an array
            based on conditional and input values.
        N)rj   r#  r   r   r   rc   r  r  r3   r9  r   rK   r  r  rJ  r	  r   r   ri   sumro  rr  )r   r	  r  noop	convertedr  r   rO  r   r   r   rJ  X  s(   


zIndex.putmaskc                 C  s   |  |rdS t|tsdS t| jrt|js|| S t|tr'|| S t| jtrBt|t	| s6dS t
t| j}||jS t|jrL|| S t| j|jS )a(  
        Determine if two Index object are equal.

        The things that are being compared are:

        * The elements inside the Index object.
        * The order of the elements inside the Index object.

        Parameters
        ----------
        other : Any
            The other object to compare against.

        Returns
        -------
        bool
            True if "other" is an Index and it has the same elements and order
            as the calling index; False otherwise.

        Examples
        --------
        >>> idx1 = pd.Index([1, 2, 3])
        >>> idx1
        Int64Index([1, 2, 3], dtype='int64')
        >>> idx1.equals(pd.Index([1, 2, 3]))
        True

        The elements inside are compared

        >>> idx2 = pd.Index(["1", "2", "3"])
        >>> idx2
        Index(['1', '2', '3'], dtype='object')

        >>> idx1.equals(idx2)
        False

        The order is compared

        >>> ascending_idx = pd.Index([1, 2, 3])
        >>> ascending_idx
        Int64Index([1, 2, 3], dtype='int64')
        >>> descending_idx = pd.Index([3, 2, 1])
        >>> descending_idx
        Int64Index([3, 2, 1], dtype='int64')
        >>> ascending_idx.equals(descending_idx)
        False

        The dtype is *not* compared

        >>> int64_idx = pd.Index([1, 2, 3], dtype='int64')
        >>> int64_idx
        Int64Index([1, 2, 3], dtype='int64')
        >>> uint64_idx = pd.Index([1, 2, 3], dtype='uint64')
        >>> uint64_idx
        UInt64Index([1, 2, 3], dtype='uint64')
        >>> int64_idx.equals(uint64_idx)
        True
        TF)rw  r	  r   rK   r   r  r\   r#  rl   r  r   r   rB   rb   )r   r   earrr   r   r   r    s    
;





zIndex.equalsc                   s4     ot fddjD ott kS )z
        Similar to equals, but checks that object attributes and types are also equal.

        Returns
        -------
        bool
            If two Index objects have equal elements and same type True,
            otherwise False.
        c                 3  s(    | ]}t |d t  |d kV  qd S r   rm  r  r   r   r   r   r    s
    
z"Index.identical.<locals>.<genexpr>)r  r.  r   r  rv  r   r  r   	identical  s   
zIndex.identicalc              	   C  s   |  | z| |}W n1 ttfy=   | j|gdd}|jdks'|jdkr+td| }|dkr8| j Y S Y | | S w t	|t
rL|t| d }| | S )aB  
        Return the label from the index, or, if not present, the previous one.

        Assuming that the index is sorted, return the passed index label if it
        is in the index, or return the previous index label if the passed one
        is not in the index.

        Parameters
        ----------
        label : object
            The label up to which the method returns the latest index label.

        Returns
        -------
        object
            The passed label if it is in the index. The previous label if the
            passed label is not in the sorted index or `NaN` if there is no
            such label.

        See Also
        --------
        Series.asof : Return the latest value in a Series up to the
            passed index.
        merge_asof : Perform an asof merge (similar to left join but it
            matches on nearest key rather than equal key).
        Index.get_loc : An `asof` is a thin wrapper around `get_loc`
            with method='pad'.

        Examples
        --------
        `Index.asof` returns the latest index label up to the passed label.

        >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03'])
        >>> idx.asof('2014-01-01')
        '2013-12-31'

        If the label is in the index, the method returns the passed label.

        >>> idx.asof('2014-01-02')
        '2014-01-02'

        If all of the labels in the index are later than the passed label,
        NaN is returned.

        >>> idx.asof('1999-01-02')
        nan

        If the index is not sorted, an error is raised.

        >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02',
        ...                            '2014-01-03'])
        >>> idx_not_sorted.asof('2013-12-31')
        Traceback (most recent call last):
        ValueError: index must be monotonic increasing or decreasing
        r  r  r   z!asof requires scalar valued inputr  )r	  r  r7  r   r  r8  r  r  r  r	  r  r  rd  )r   rb  r  r  r   r   r   asof  s    
9

z
Index.asofr  r	  c                 C  sr   | j | j|j dd}t|dk|d d}tjt| tjd| |}| j |  }d||dk|j |k @ < |S )a  
        Return the locations (indices) of labels in the index.

        As in the `asof` function, if the label (a particular entry in
        `where`) is not in the index, the latest index label up to the
        passed label is chosen and its index returned.

        If all of the labels in the index are later than a label in `where`,
        -1 is returned.

        `mask` is used to ignore NA values in the index during calculation.

        Parameters
        ----------
        where : Index
            An Index consisting of an array of timestamps.
        mask : np.ndarray[bool]
            Array of booleans denoting where values in the original
            data are not NA.

        Returns
        -------
        np.ndarray[np.intp]
            An array of locations (indices) of the labels from the Index
            which correspond to the return values of the `asof` function
            for every element in `where`.
        r  r
  r   r   r  r  )	r#  searchsortedr   r  re  rd  r  r  argmax)r   r  r	  locsr4  first_valuer   r   r   	asof_locs:  s   
!zIndex.asof_locslastr<  r=  na_positionc                 C  sZ   t | |}t| tst||||d}n| }|s |ddd }| |}|r+||fS |S )a  
        Return a sorted copy of the index.

        Return a sorted copy of the index, and optionally return the indices
        that sorted the index itself.

        Parameters
        ----------
        return_indexer : bool, default False
            Should the indices that would sort the index be returned.
        ascending : bool, default True
            Should the index values be sorted in an ascending order.
        na_position : {'first' or 'last'}, default 'last'
            Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
            the end.

            .. versionadded:: 1.2.0

        key : callable, optional
            If not None, apply the key function to the index values
            before sorting. This is similar to the `key` argument in the
            builtin :meth:`sorted` function, with the notable difference that
            this `key` function should be *vectorized*. It should expect an
            ``Index`` and return an ``Index`` of the same shape.

            .. versionadded:: 1.1.0

        Returns
        -------
        sorted_index : pandas.Index
            Sorted copy of the index.
        indexer : numpy.ndarray, optional
            The indices that the index itself was sorted by.

        See Also
        --------
        Series.sort_values : Sort values of a Series.
        DataFrame.sort_values : Sort values in a DataFrame.

        Examples
        --------
        >>> idx = pd.Index([10, 100, 1, 1000])
        >>> idx
        Int64Index([10, 100, 1, 1000], dtype='int64')

        Sort values in ascending order (default behavior).

        >>> idx.sort_values()
        Int64Index([1, 10, 100, 1000], dtype='int64')

        Sort values in descending order, and also get the indices `idx` was
        sorted by.

        >>> idx.sort_values(ascending=False, return_indexer=True)
        (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))
        )itemsr=  r  r  Nr  )rz   r	  r\   r|   argsortr  )r   r<  r=  r  r  r1  _assorted_indexr   r   r   r>  g  s   
?

zIndex.sort_valuesc                 O  r  )z*
        Use sort_values instead.
        z=cannot sort an Index object in-place, use sort_values insteadr  r   rU  r   r   r   r   r     r  z
Index.sortc                 C  s   t dt| j )a  
        Shift index by desired number of time frequency increments.

        This method is for shifting the values of datetime-like indexes
        by a specified time increment a given number of times.

        Parameters
        ----------
        periods : int, default 1
            Number of periods (or increments) to shift by,
            can be positive or negative.
        freq : pandas.DateOffset, pandas.Timedelta or str, optional
            Frequency increment to shift by.
            If None, the index is shifted by its own `freq` attribute.
            Offset aliases are valid strings, e.g., 'D', 'W', 'M' etc.

        Returns
        -------
        pandas.Index
            Shifted index.

        See Also
        --------
        Series.shift : Shift values of Series.

        Notes
        -----
        This method is only implemented for datetime-like index classes,
        i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex.

        Examples
        --------
        Put the first 5 month starts of 2011 into an index.

        >>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS')
        >>> month_starts
        DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01',
                       '2011-05-01'],
                      dtype='datetime64[ns]', freq='MS')

        Shift the index by 10 days.

        >>> month_starts.shift(10, freq='D')
        DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11',
                       '2011-05-11'],
                      dtype='datetime64[ns]', freq=None)

        The default value of `freq` is the `freq` attribute of the index,
        which is 'MS' (month start) in this example.

        >>> month_starts.shift(10)
        DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01',
                       '2012-03-01'],
                      dtype='datetime64[ns]', freq='MS')
        z\This method is only implemented for DatetimeIndex, PeriodIndex and TimedeltaIndex; Got type )rJ  r  r  )r   periodsfreqr   r   r   shift  s
   8zIndex.shiftc                 O  s   | j j|i |S )aK  
        Return the integer indices that would sort the index.

        Parameters
        ----------
        *args
            Passed to `numpy.ndarray.argsort`.
        **kwargs
            Passed to `numpy.ndarray.argsort`.

        Returns
        -------
        np.ndarray[np.intp]
            Integer indices that would sort the index if used as
            an indexer.

        See Also
        --------
        numpy.argsort : Similar method for NumPy arrays.
        Index.sort_values : Return sorted copy of Index.

        Examples
        --------
        >>> idx = pd.Index(['b', 'a', 'd', 'c'])
        >>> idx
        Index(['b', 'a', 'd', 'c'], dtype='object')

        >>> order = idx.argsort()
        >>> order
        array([1, 0, 3, 2])

        >>> idx[order]
        Index(['a', 'b', 'c', 'd'], dtype='object')
        )r   r  r  r   r   r   r    s   %zIndex.argsortseriesc                 C  sd   t jdtt d | | z| |}W n ty*   | js  t|r'|}n Y nw | 	|||S )z
        Fast lookup of value from 1-dimensional ndarray.

        Only use this if you know what you're doing.

        Returns
        -------
        scalar or Series
        zYget_value is deprecated and will be removed in a future version. Use Series[key] instead.r   )
r  r  r  r0   r  r  r7  r"  rF   _get_values_for_loc)r   r  r  r  r   r   r   	get_value%  s"   

zIndex.get_valuec                 C  s   t |st|d S r   )rL   r+   r  r   r   r   r  L  s   zIndex._check_indexing_errorc                 C  s
   |    S )zA
        Should an integer key be treated as positional?
        )rm  r   r   r   r   r"  R  rn  z$Index._should_fallback_to_positionalc                 C  s   t |r	|j| S |j| S )z
        Do a positional lookup on the given Series, returning either a scalar
        or a Series.

        Assumes that `series.index is self`

        key is included for MultiIndex compat.
        )rF   r#  r  )r   r  r  r  r   r   r   r  Y  s   	

zIndex._get_values_for_locc                 C  s8   t jdtt d | j|}t||st|||< dS )z
        Fast lookup of value from 1-dimensional ndarray.

        .. deprecated:: 1.0

        Notes
        -----
        Only use this if you know what you're doing.
        zNThe 'set_value' method is deprecated, and will be removed in a future version.r   N)r  r  r  r0   rx  r  r4   r9  )r   r6  r  r  r  r   r   r   r   g  s   
zIndex.set_valuea  
        Compute indexer and mask for new index given the current index.

        The indexer should be then used as an input to ndarray.take to align the
        current data to the new index.

        Parameters
        ----------
        target : %(target_klass)s

        Returns
        -------
        indexer : np.ndarray[np.intp]
            Integers from 0 to n - 1 indicating that the index at these
            positions matches the corresponding target values. Missing values
            in the target are marked by -1.
        missing : np.ndarray[np.intp]
            An indexer into the target of the values not found.
            These correspond to the -1 in the indexer array.
        r  1tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]c                 C  s   t |}| |}| |st| js| j|d ddS | |\}}|| us*||ur/||S t| j|jsN| 	|}| j
|dd}|j
|dd}||S | }| jr`|jr`| j}||}| j|\}	}
t|	t|
fS )NFr  r   )r0  r  r  rG   r   r  r  r  r@   r  r  r   rS  rx  r  r=   )r   r  r  r  r   r  r  r  r  r  rf   r   r   r   r    s$   




zIndex.get_indexer_non_uniquec                 C  s"   | j r| |S | |\}}|S )a  
        Guaranteed return of an indexer even when non-unique.

        This dispatches to get_indexer or get_indexer_non_unique
        as appropriate.

        Returns
        -------
        np.ndarray[np.intp]
            List of indices.

        Examples
        --------
        >>> idx = pd.Index([np.nan, 'var1', np.nan])
        >>> idx.get_indexer_for([np.nan])
        array([0, 2])
        )r  r  r  )r   r  r  r  r   r   r   r    s   
zIndex.get_indexer_for	axis_nametuple[Index, np.ndarray]c                 C  s   |}t |tst|}| jr| |}| |d }n| |\}}}| ||| | 	|}t |tr9|j
|_
|jjdv rUt |tsPt |t| rU|jdu rU|d}||fS )zR
        Analogue to get_indexer that raises if any elements are missing.
        r   rv  N)r	  r   r&  r'  r  r  r4  r>  _raise_if_missingr  r   r   r$  r-  r  r  
_with_freq)r   r  r  keyarrr  r9  r   r   r   _get_indexer_strict  s&   






zIndex._get_indexer_strictc                 C  s   t |dkrdS |dk }| }|rNt| jp!t| jo!t| jj}|t |kr9|r.t|}td| d| dtt||	 d  
 }t| ddS )a8  
        Check that indexer can be used to return a result.

        e.g. at least one element was found,
        unless the list of keys was actually empty.

        Parameters
        ----------
        key : list-like
            Targeted labels (only used to show correct error message).
        indexer: array-like of booleans
            Indices corresponding to the key,
            (with -1 indicating not found).
        axis_name : str

        Raises
        ------
        KeyError
            If at least one key was requested but none was found.
        r   Nz	None of [z] are in the []z not in index)rd  r  rG   r   r?   r  r-  r7  r0  r  r   )r   r  r  r  missing_masknmissinguse_interval_msg	not_foundr   r   r   r    s$   

zIndex._raise_if_missingr   c                 C  rA  r   r   r   r  r  r   r   r   r   r  "  r5  z!Index._get_indexer_non_comparablec                 C  rA  r   r   r  r   r   r   r  (  r5  Hnpt.NDArray[np.intp] | tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]c                 C  rA  r   r   r  r   r   r   r  .  r5  c                 C  sb   |durt |}td| j d|j dtj|jtjd }|r#|S tjt|tjd}||fS )a  
        Called from get_indexer or get_indexer_non_unique when the target
        is of a non-comparable dtype.

        For get_indexer lookups with method=None, get_indexer is an _equality_
        check, so non-comparable dtypes mean we will always have no matches.

        For get_indexer lookups with a method, get_indexer is an _inequality_
        check, so non-comparable dtypes mean we will always raise TypeError.

        Parameters
        ----------
        target : Index
        method : str or None
        unique : bool, default True
            * True if called from get_indexer.
            * False if called from get_indexer_non_unique.

        Raises
        ------
        TypeError
            If doing an inequality check, i.e. method is not None.
        NzCannot compare dtypes z and r  r  )	r  r   r   r   onesshaper  re  rd  )r   r  r  r   r   
no_matchesrf   r   r   r   r  4  s   c                 C  r  )z
        Whether we should treat this as unique for the sake of
        get_indexer vs get_indexer_non_unique.

        For IntervalIndex compat.
        r\  r   r   r   r   r  \  s   zIndex._index_as_uniquez8Reindexing only valid with uniquely valued Index objectstuple[Index, Index]c              	   C  sR  t | tr&t |tr&| jdur%|jdur%t| j|js%| d|dfS nn| jdkrGt |trGz	t|| |fW S  tyF   | |f Y S w | jdkrYt |trYt|| |fS | j	j
dkrt|j	j
dkrt| dkrs| || j	fS n | jr|jsz	t| |}W n ttfy   t| j} Y nw t| j	st|j	r|| \}} | |fS )z
        When dealing with an object-dtype Index and a non-object Index, see
        if we can upcast the object-dtype one to improve performance.
        NUTCdate	timedeltar  r  r   )r	  r[   r   r   
tz_convertr  r  r   r`   r   r$  minr  rS  r0  r   r9  r   r#  rK   r  rv  r   r   r   r  h  s<   zIndex._maybe_promotec                 C  s   t || jrt| j}t| j|rtd|S t|dd\}}| jdks(|dkr3t| js1t|r3tS t| j|g}t	| |g|}|S )zk
        Implementation of find_common_type that adjusts for Index-specific
        special cases.
        zOThis should not be reached. Please report a bug at github.com/pandas-dev/pandasT)rQ   uint64)
rc   r   r6   r@   rJ  r8   rM   r(  r7   r5   )r   r  r   target_dtyper  r   r   r   r    s    
zIndex._find_common_type_compatc                 C  sD   |  r|  s|   r| rdS t|}|j}| |p!t|S )zK
        Check if `self == other` can ever have non-False entries.
        F)ra  rg  r  r   _is_comparable_dtyperK   )r   r   r   r   r   r   r    s   zIndex._should_comparec                 C  s,   | j jdkr|jdkS t| j rt|S dS )zF
        Can we compare values of the given dtype to our own?
        r  T)r   r$  rJ   r  r   r   r   r    s
   

zIndex._is_comparable_dtype PrettyDict[Hashable, np.ndarray]c                   s>   t |tr|j}t|}| } fdd| D }t|S )a
  
        Group the index labels by a given array of values.

        Parameters
        ----------
        values : array
            Values used to determine the groups.

        Returns
        -------
        dict
            {group name -> group labels}
        c                   s   i | ]
\}}|  |qS r   )r  r  r   r   r   ro    s    z!Index.groupby.<locals>.<dictcomp>)r	  r\   r#  rk   _reverse_indexerr  r~   )r   rO  r4  r   r   r   rf    s   
zIndex.groupbyc                 C  s   ddl m} | j||d}|jr7t|d tr7t| |r | j}n| jr.| jgt|d  }nd}|j	||dS d}|js?| j
}tj|dd| jk}|rSt|| j
|d}| jret|j
re| j||d| jd	S tj||d| jd	S )
aV  
        Map values using an input mapping or function.

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

        Returns
        -------
        applied : Union[Index, MultiIndex], inferred
            The output of the mapping function applied to the index.
            If the function returns a tuple with more than one element
            a MultiIndex will be returned.
        r   r  )	na_actionNr  Fro  )
same_dtyper   )r/  r   _map_valuesr  r	  r
  r  r   rd  r0  r   r   rq  r  r9   r   rJ   r"  r   rV  )r   rP  r  r   r  r  r   r  r   r   r   r    s0   

z	Index.mapc                  sp   t | tr'dur fdd| D }n	 fdd| D }t| j|| jdS  fdd| D }t|| jddS )	z
        Apply function to all values found in index.

        This includes transforming multiindex entries separately.
        Only apply function to one level of the MultiIndex if level is specified.
        Nc                   s(   g | ]}t  fd dt|D qS )c                 3  s(    | ]\}}|kr |n|V  qd S r   r   )r  r  yfuncr   r   r   r  4     & 4Index._transform_index.<locals>.<listcomp>.<genexpr>)r
  r  r  r  r   r   r  3  s    z*Index._transform_index.<locals>.<listcomp>c                   s"   g | ]}t  fd d|D qS )c                 3  s    | ]} |V  qd S r   r   )r  r  r  r   r   r  8  r  r  )r
  r  r  r   r   r  8  s   " r  c                   s   g | ]} |qS r   r   r  r  r   r   r  ;  r  F)r   r2  )r	  r\   r  r0  r  r   r   )r   r  r   r  r   r  r   _transform_index(  s   
zIndex._transform_indexc                 C  s    |dur	|  | t| j|S )a
  
        Return a boolean array where the index values are in `values`.

        Compute boolean array of whether each index value is found in the
        passed set of values. The length of the returned boolean array matches
        the length of the index.

        Parameters
        ----------
        values : set or list-like
            Sought values.
        level : str or int, optional
            Name or position of the index level to use (if the index is a
            `MultiIndex`).

        Returns
        -------
        np.ndarray[bool]
            NumPy array of boolean values.

        See Also
        --------
        Series.isin : Same for Series.
        DataFrame.isin : Same method for DataFrames.

        Notes
        -----
        In the case of `MultiIndex` you must either specify `values` as a
        list-like object containing tuples that are the same length as the
        number of levels, or specify `level`. Otherwise it will raise a
        ``ValueError``.

        If `level` is specified:

        - if it is the name of one *and only one* index level, use that level;
        - otherwise it should be a number indicating level position.

        Examples
        --------
        >>> idx = pd.Index([1,2,3])
        >>> idx
        Int64Index([1, 2, 3], dtype='int64')

        Check whether each index value in a list of values.

        >>> idx.isin([1, 4])
        array([ True, False, False])

        >>> midx = pd.MultiIndex.from_arrays([[1,2,3],
        ...                                  ['red', 'blue', 'green']],
        ...                                  names=('number', 'color'))
        >>> midx
        MultiIndex([(1,   'red'),
                    (2,  'blue'),
                    (3, 'green')],
                   names=['number', 'color'])

        Check whether the strings in the 'color' level of the MultiIndex
        are in a list of colors.

        >>> midx.isin(['red', 'orange', 'yellow'], level='color')
        array([ True, False, False])

        To check across the levels of a MultiIndex, pass a list of tuples:

        >>> midx.isin([(1, 'red'), (3, 'red')])
        array([ True, False, False])

        For a DatetimeIndex, string values in `values` are converted to
        Timestamps.

        >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13']
        >>> dti = pd.to_datetime(dates)
        >>> dti
        DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'],
        dtype='datetime64[ns]', freq=None)

        >>> dti.isin(['2000-03-11'])
        array([ True, False, False])
        N)r9  r   isinr#  r)  r   r   r   r  >  s   Q
z
Index.isinc                 C  s   t r   )rJ  r  r   r   r   _get_string_slice  s   zIndex._get_string_slicer   endr  c                 C  sN   |  |dd | j|||d\}}t|stdt|s!tdt|||S )aG  
        Compute the slice indexer for input labels and step.

        Index needs to be ordered and unique.

        Parameters
        ----------
        start : label, default None
            If None, defaults to the beginning.
        end : label, default None
            If None, defaults to the end.
        step : int, default None
        kind : str, default None

            .. deprecated:: 1.4.0

        Returns
        -------
        indexer : slice

        Raises
        ------
        KeyError : If key does not exist, or key is not unique and index is
            not ordered.

        Notes
        -----
        This function assumes that the data is sorted, so use at your own peril

        Examples
        --------
        This is a method on all index types. For example you can do:

        >>> idx = pd.Index(list('abcd'))
        >>> idx.slice_indexer(start='b', end='c')
        slice(1, 3, None)

        >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')])
        >>> idx.slice_indexer(start='b', end=('c', 'g'))
        slice(1, 3, None)
        r$  r%  )r  zStart slice bound is non-scalarzEnd slice bound is non-scalar)_deprecated_arg
slice_locsrL   AssertionErrorr  )r   r   r  r  r$  start_slice	end_slicer   r   r   r%    s   0zIndex.slice_indexerc                 C  r  )zx
        If we have a float key and are not a floating index, then try to cast
        to an int if equivalent.
        r   r  r   r   r   r    r  zIndex._maybe_cast_indexerc                 C  s   t |S )zT
        Analogue to maybe_cast_indexer for get_indexer instead of get_loc.
        )r0  r  r   r   r   r    r  z"Index._maybe_cast_listlike_indexerc                 C  s0   |dv sJ |durt |s| ||dS dS )zz
        If we are positional indexer, validate that we have appropriate
        typed bounds must be an integer.
        )r   r  N)rF   r+  )r   r*  r  r$  r   r   r   r    s   zIndex._validate_indexerr
  c                 C  sJ   |dddt fv s
J | |dd t|st|r#|| vr#| d||S )a  
        This function should be overloaded in subclasses that allow non-trivial
        casting on label-slice bounds, e.g. datetime-like indices allowing
        strings containing formatted datetimes.

        Parameters
        ----------
        label : object
        side : {'left', 'right'}
        kind : {'loc', 'getitem'} or None

            .. deprecated:: 1.3.0

        Returns
        -------
        label : object

        Notes
        -----
        Value of `side` parameter should be validated in caller.
        r  r   Nr$  _maybe_cast_slice_boundr  )r   r  rC   rF   r+  )r   rb  r
  r$  r   r   r   r    s
   zIndex._maybe_cast_slice_boundLiteral['left', 'right']c                 C  sR   | j r
| j||dS | jr%| d d d j||dkrdndd}t| | S td)Nr  r  r   r  z0index must be monotonic increasing or decreasing)rT  r  rW  rd  r9  )r   rb  r
  posr   r   r   r	    s   zIndex._searchsorted_monotonicc                 C  s  |dddt fv s
J | |dd |dvrtd| |}| ||}z| |}W n# tyN } zz| ||W W  Y d}~S  tyI   |w d}~ww t|tj	rvt
|js\J t|d}t|tj	rvtd	| d
t| t|tr|dkr|jS |jS |dkr|d S |S )a  
        Calculate slice bound that corresponds to given label.

        Returns leftmost (one-past-the-rightmost if ``side=='right'``) position
        of given label.

        Parameters
        ----------
        label : object
        side : {'left', 'right'}
        kind : {'loc', 'getitem'} or None

            .. deprecated:: 1.4.0

        Returns
        -------
        int
            Index of label.
        r  r   Nr$  get_slice_bound)r   r  z@Invalid value for side kwarg, must be either 'left' or 'right': u1zCannot get z# slice bound for non-unique label: r   r  r   )r   r  r9  r  r  r7  r	  r	  r   r   r>   r   r   maybe_booleans_to_slicer  r   r  r   r  )r   rb  r
  r$  original_labelslcr  r   r   r   r    sH   
zIndex.get_slice_boundtuple[int, int]c           
   	   C  s  |  |dd |du p|dk}|s||}}t|ttfrEt|ttfrEz
t|}t|}W n ttfy9   Y nw t|j|jsEtdd}|durQ| 	|d}|du rWd}d}	|durc| 	|d}	|	du rkt
| }	|s|d |	d }	}|	d	kr|	t
| 8 }	|d	kr|t
| 8 }||	fS )
a  
        Compute slice locations for input labels.

        Parameters
        ----------
        start : label, default None
            If None, defaults to the beginning.
        end : label, default None
            If None, defaults to the end.
        step : int, defaults None
            If None, defaults to 1.
        kind : {'loc', 'getitem'} or None

            .. deprecated:: 1.4.0

        Returns
        -------
        start, end : int

        See Also
        --------
        Index.get_loc : Get location for a single label.

        Notes
        -----
        This method only works if the index is monotonic or unique.

        Examples
        --------
        >>> idx = pd.Index(list('abcd'))
        >>> idx.slice_locs(start='b', end='c')
        (1, 3)
        r$  r  Nr   z(Both dates must have the same UTC offsetr   r  r   r  )r  r	  r   r   r   r9  r   r   tzinfor  rd  )
r   r   r  r  r$  incts_startts_endr  r  r   r   r   r  a  s<   $
zIndex.slice_locsc                 C  s<   | j }t|tjrt||}n||}| jj|| jdS )a  
        Make new Index with passed location(-s) deleted.

        Parameters
        ----------
        loc : int or list of int
            Location of item(-s) which will be deleted.
            Use a list of locations to delete more than one value at the same time.

        Returns
        -------
        Index
            Will be same type as self, except for RangeIndex.

        See Also
        --------
        numpy.delete : Delete any rows and column from NumPy array (ndarray).

        Examples
        --------
        >>> idx = pd.Index(['a', 'b', 'c'])
        >>> idx.delete(1)
        Index(['a', 'c'], dtype='object')

        >>> idx = pd.Index(['a', 'b', 'c'])
        >>> idx.delete([0, 2])
        Index(['b'], dtype='object')
        r   )r#  r	  r   r   deleter"  r!  r   )r   r  rO  r  r   r   r   r	    s
   
zIndex.deleter  c              
   C  s,  t |}t|| jr| jtkr| j}| j}zt|tr-|	||}t
| j|| jdW S | |}W n tttfyM   | |}| |	|| Y S w |jtks]t|ttjtjfsk|j
|}t	|||}nt	||d}|dkrx|n|d }|||< | jdkr| jj|| jdS tj|| jdS )a  
        Make new Index inserting new item at location.

        Follows Python numpy.insert semantics for negative values.

        Parameters
        ----------
        loc : int
        item : object

        Returns
        -------
        new_index : Index
        r   Nr   r   numericindex)r   r  rc   r   r   r  r#  r	  rl   insertr  r!  r   r  r   r9  r3   r  r  r
  r   
datetime64timedelta64r   r"  rV  r   )r   r  r  r6  r  r   castedr  r   r   r   r    s0   



zIndex.insertraiser   'Index | np.ndarray | Iterable[Hashable]errorsr$   c                 C  sv   t |ts| jdkrdnd}tj||d}| |}|dk}| r6|dkr1tt||  d||  }| 	|S )a  
        Make new Index with passed list of labels deleted.

        Parameters
        ----------
        labels : array-like or scalar
        errors : {'ignore', 'raise'}, default 'raise'
            If 'ignore', suppress error and existing labels are dropped.

        Returns
        -------
        dropped : Index
            Will be same type as self, except for RangeIndex.

        Raises
        ------
        KeyError
            If not all of the labels are found in the selected axis
        r   Nr  r  rP  z not found in axis)
r	  r   r   r&  index_labels_to_arrayr  r  r7  r-  r	  )r   r   r  	arr_dtyper  r	  r   r   r   drop   s   



z
Index.dropc                 C  s  |  |rF|tjtjtjhv r(tjt| td}| j	r&t
| ts&d||  < |S |tju rFtjt| td}| j	rDt
| tsDd||  < |S t
|tjtttfr\t| t|kr\tdt
|tsht|dd}nt|}t| jrt
|trtjdd || j|}W d   |S 1 sw   Y  |S t
| jtr|| j|}|S t| jrt
| tstjdd t|| j|}W d   |S 1 sw   Y  |S tjdd t| j||}W d   |S 1 sw   Y  |S )	zA
        Wrapper used to dispatch comparison operations.
        r  FTzLengths must match to comparer   rP  r.  N)rw  r  eqr  ger   r  rd  r   r  r	  r\   rd   ner  r   r   r_   rl   r9  rt   r%  rK   r   errstater#  rg   comp_method_OBJECT_ARRAYcomparison_op)r   r   r  r6  r4  r   r   r   _cmp_methodH  sV   






zIndex._cmp_methodc                 C  s<   t |trtj|d |dtj|d |dfS tj||dS )Nr   r   r   )r	  r
  r   rV  )r   r4  r   r   r   r   _construct_resultw  s
   
zIndex._construct_resultc                   s2   t |trt|jrt|turtS t ||S r   )r	  r   rK   r   r  r  r  _arith_method)r   r   r  r  r   r   r    s   
zIndex._arith_methodc                 C  s   || j }t|| jdS r  )r#  r   r   )r   r  r4  r   r   r   _unary_method  s   
zIndex._unary_methodc                 C     |  tjS r   )r  r  r  r   r   r   r   __abs__  r(  zIndex.__abs__c                 C  r   r   )r  r  negr   r   r   r   __neg__  r(  zIndex.__neg__c                 C  r   r   )r  r  r  r   r   r   r   __pos__  r(  zIndex.__pos__c                 C  r   r   )r  r  invr   r   r   r   
__invert__  r  zIndex.__invert__c                 O  "   t || | d t| jS )at  
        Return whether any element is Truthy.

        Parameters
        ----------
        *args
            Required for compatibility with numpy.
        **kwargs
            Required for compatibility with numpy.

        Returns
        -------
        any : bool or array-like (if axis is specified)
            A single element array-like may be converted to bool.

        See Also
        --------
        Index.all : Return whether all elements are True.
        Series.all : Return whether all elements are True.

        Notes
        -----
        Not a Number (NaN), positive infinity and negative infinity
        evaluate to True because these are not equal to zero.

        Examples
        --------
        >>> index = pd.Index([0, 1, 2])
        >>> index.any()
        True

        >>> index = pd.Index([0, 0, 0])
        >>> index.any()
        False
        r  )r  validate_any_maybe_disable_logical_methodsr   r  rO  r  r   r   r   r    s   $
z	Index.anyc                 O  r'  )a  
        Return whether all elements are Truthy.

        Parameters
        ----------
        *args
            Required for compatibility with numpy.
        **kwargs
            Required for compatibility with numpy.

        Returns
        -------
        all : bool or array-like (if axis is specified)
            A single element array-like may be converted to bool.

        See Also
        --------
        Index.any : Return whether any element in an Index is True.
        Series.any : Return whether any element in a Series is True.
        Series.all : Return whether all elements in a Series are True.

        Notes
        -----
        Not a Number (NaN), positive infinity and negative infinity
        evaluate to True because these are not equal to zero.

        Examples
        --------
        True, because nonzero integers are considered True.

        >>> pd.Index([1, 2, 3]).all()
        True

        False, because ``0`` is considered False.

        >>> pd.Index([0, 1, 2]).all()
        False
        r.  )r  validate_allr)  r   r.  rO  r  r   r   r   r.    s   '
z	Index.allopnamec                 C  sF   t | tst| jst| jst| jst| jr!t||  dS dS )zK
        raise if this Index subclass does not support any or all.
        N)r	  r\   rP   r   rG   r?   rD   ry   )r   r+  r   r   r   r)    s   z$Index._maybe_disable_logical_methodsc                   F   t || t | | js| jr| j}|r| rdS t j|dS Nr  ro  )	r  validate_argminvalidate_minmax_axisrS  r|  r{  r.  r  argminr   r  rp  rU  r   r	  r  r   r   r0       
zIndex.argminc                   r,  r-  )	r  validate_argmaxr/  rS  r|  r{  r.  r  r  r1  r  r   r   r    r2  zIndex.argmaxc                      t || t | t| s| jS t| r#| jr#| d }t|s#|S | js5| jr5| j	}|r2|
 r5| jS | jsFt| jtjsF| jj|dS t j|dS )Nr   ro  )r  validate_minr/  rd  r  rT  rd   rS  r|  r{  r.  r	  r#  r   r   r  r  )r   r  rp  rU  r   r_  r	  r  r   r   r  #     
z	Index.minc                   r4  r-  )r  validate_maxr/  rd  r  rT  rd   rS  r|  r{  r.  r	  r#  r   r   r  r  )r   r  rp  rU  r   r  r	  r  r   r   r  =  r6  z	Index.maxr&   c                 C  s
   t | fS )zE
        Return a tuple of the shape of the underlying data.
        )rd  r   r   r   r   r  Y  s   
zIndex.shape
methodnamec                 C  s0   |t urtjd| d| dtt d dS dS )zK
        Issue a FutureWarning if the arg/kwarg is not no_default.
        r  z' argument in zH is deprecated and will be removed in a future version.  Do not pass it.r   N)r   r  r  r  r0   )r   r  r   r8  r   r   r   r  b  s   
zIndex._deprecated_arg)r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   )NNFNTr   r   )r   r   )r   r"   r   )r   rL  r   r	   r   r   )r   r   r   rL  )r   r   )r   r   )r   rl  )r   r   r   r	   r   r   )r   r   r   r   )r   r   )r   r{  )r   r  )r   r  )r   r   )r  r  r  r   )r   r"   )r  T)r   TN)r  r  r  r   )r  r   r   r   )NFNN)r   r   r   r  r  r   r   r  r  r  r   r   )r   r   )r   r  )r   r  )FNr  )r   r   r  r  r  r   r   r  )r  r  r  r   r   r  )r   r  )NN)r   r	   r   r   )r   r   r   r	   r   r   r   r	   )r  r	   r   r   )NNF)r  r   r   r  )r  r#  r   r  )r   rw   r  )r   r   F)NTN)r   )rE  rG  )rN  r   r   rO  )r   rx  )r  )r   r   r   r   r   r   )r   r   r   r  r   r   )r_  )r   r   ra  r  r   r   )ra  r  r   rx  )r   r   )r   r   r  r   )r   r   )r   r   r   r   )r   r   r   r   )r   r  )NNN)r  r  r  r  r   r   )r  r   r  r  r  r  r   r   )r  r   r   r   )r  r  r  r  r   r   )r  r  r   r   )r  r   r  r   r  r  r   r   )r  r   r  r  r   r   )r  r   r  r   r   r   )r  r   r  r   r   r   )r  r  r   r   )r  r  r$  r   r  r   )r*  r   r   r   )r  r   r   r   )NNNN)r   r-  )r3  r   )r  r   r3  r   )r  r   r   r6  )r   r   r   r   r   r%   r   r?  r   r   r   r@  )r   r   r   r   r   r%   r   rE  r   r   r   r   )r   r   r   r   r   r%   r   r   r   r   r   rF  r   )r   r   r   r   r   r   r   r@  )r   r   r   r   )r   )r   r   r   r   r   rm  )r   T)r   r   r   r   r.  r   r   rt  )r   r   r   r   r   r@  )r   r   r   r   r   r   r   r   )r   r   )r   rl   )r   r   )r4  r   r   r   )r  r   r   r  )r$  r   r   r   )r  r   r   r   )r   r   r  r  r   r   )r   r  r   r   )r  r  r   r	   r   r   )r   r   r   r   )r  r   r	  rx  r   r   )FTr  N)r<  r   r=  r   r  r   r  r  r   N)r   r   )r  r   )r   r  )r  r   r   r  )r  r   r   r   ).)r  r   r   r?  r   r   )r  r   r   rE  r   r  )r  r   r   r   r   r  )r   r   r   r  )r   r   r   r   )r   r"   r   r   )r   r  )r  r   )r   r  r  r  r  r  r   r  )r*  r   r$  r   )r
  r   )r
  r  )r
  r  r   r  )r   r  )r  r  r   r   )r  )r   r  r  r$   r   r   )r+  r   r   r   )NT)r   r&   )r   r   r8  r   r   r   (  r  
__module____qualname____doc__rr   r   rq   	frozenset__annotations__rO  r   r   r   r   r   r   r   r   rl   r   r   r   r   r   r   r   r   r   propertyr   !_supports_partial_string_indexing
_accessorsrh   r}   r   r   classmethodr*  r  rK  r!  rV  r-   r"  r]  rZ  rq  r   rr  rt  ru  rw  rN  rz  rx  r  r  r  r  r  r   r  r  r  r   r,   r   r  r  r  r   r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r   rj  r   setterr  r&  r'  r*  r  r.   r2  r3  rh  r4  r9  r;  r@  rA  get_level_valuesrF  rD  rR  r  rU  rT  rW  rY  r[  rY  r]  ra  rF   re  rg  r  rh  rj  rl  rm  r  rs  rt  rS  ru  r  r{  r|  rd   isnullr}  notnullr  rN  r   r  r   r  r  r  r  r  __bool__r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r)  r+  r,  r4  r2  r5  r>  r   r   r   rT  rM  rQ  r1  rR  rp  r  rO  r/   r  r#  r   r   r  r  r  r+  r  r  r~  r  r  r  r  r  r  r  r  r  rJ  r  r  r  r  r>  r   r  r  r  r  r"  r  r   r  r  r  r  r  r  r  r  r  r  r  rf  r  r  r  r  r%  r  r  r  r  r	  r  r  r	  r  r  r  r  r  r  r!  r#  r$  r&  r  r.  r)  r0  r  r  r  r  r  __classcell__r   r   r  r   r     s  
 0

	
 D

"	'
V'?

'&@K
!#n6!'3='##++(+!%		7,%4@


tE	N6XS5X- !	swM|"Q -(	,4*WK/S='&$0'	-!
9U<
"F^(<(/,/

c                 C  sH   ddl m} t| dkr|dur|d }tj| d |dS |j| |dS )a  
    Construct an index from sequences of data.

    A single sequence returns an Index. Many sequences returns a
    MultiIndex.

    Parameters
    ----------
    sequences : sequence of sequences
    names : sequence of str

    Returns
    -------
    index : Index or MultiIndex

    Examples
    --------
    >>> ensure_index_from_sequences([[1, 2, 3]], names=["name"])
    Int64Index([1, 2, 3], dtype='int64', name='name')

    >>> ensure_index_from_sequences([["a", "a"], ["a", "b"]], names=["L1", "L2"])
    MultiIndex([('a', 'a'),
                ('a', 'b')],
               names=['L1', 'L2'])

    See Also
    --------
    ensure_index
    r   r  r   Nr   r  )r/  r   rd  r   rV  from_arrays)	sequencesr  r   r   r   r   ensure_index_from_sequencesp  s   rO  F
index_liker    r   r   c                 C  s   t | tr|r|  } | S t | tr| j}tj| ||dS t| r%t| } t | trPt| tur4t| } t	| rHt
| rHddlm} || S tj| |ddS tj| |dS )ak  
    Ensure that we have an index from some index-like object.

    Parameters
    ----------
    index_like : sequence
        An Index or other sequence
    copy : bool, default False

    Returns
    -------
    index : Index or MultiIndex

    See Also
    --------
    ensure_index_from_sequences

    Examples
    --------
    >>> ensure_index(['a', 'b'])
    Index(['a', 'b'], dtype='object')

    >>> ensure_index([('a', 'a'),  ('b', 'c')])
    Index([('a', 'a'), ('b', 'c')], dtype='object')

    >>> ensure_index([['a', 'a'], ['b', 'c']])
    MultiIndex([('a', 'b'),
            ('a', 'c')],
           )
    r   r   r  F)r   r2  r   )r	  r   r   r_   r   rV  rH   r-  r  rd  r   is_all_arrayliker/  r   rM  )rP  r   r   r   r   r   r   r0    s"   



r0  c                 C  s*   zt |  W | S  ty   t|  Y S w )z<
    If seq is an iterator, put its values into a list.
    )rd  r   r-  )seqr   r   r   r/    s   
r/  stringsr   c                 C  sN   | s| S t | r%t dd | D r%dd | D } t | r%t dd | D s| S )z
    Trims zeros and decimal points.

    Examples
    --------
    >>> trim_front([" a", " b"])
    ['a', 'b']

    >>> trim_front([" a", " "])
    ['a', '']
    c                 s  s    | ]	}|d  dkV  qdS )r   r  Nr   r  r   r   r   r    s    ztrim_front.<locals>.<genexpr>c                 S  s   g | ]}|d d qS r=  r   r  r   r   r   r    r  ztrim_front.<locals>.<listcomp>r  )rS  r   r   r   r    s   r  r  r   c                 C  s   | dvrt d|  d S )N)r   r  rI  rH  zdo not recognize join method r  r  r   r   r   rP    s   rP  r	   c                 C  s8   | du rt |ttfr|j} t| st|j d| S )zR
    If no name is passed, then extract it from data, validating hashability.
    Nz.name must be a hashable type)r	  r   r_   r   rE   r   r  )r   r  r   r   r   r   r    s
   r  zIn a future version, passing an object-dtype arraylike to pd.Index will not infer numeric values to numeric dtype (matching the Series behavior). To retain the old behavior, explicitly pass the desired dtype or use the desired Index subclassTr7  r  r   c              	   C  sN   t j| ddddtdd}|jjdv r!|s|S tjdtt d t	|}|S )aR  
    If we have an arraylike input but no passed dtype, try to infer
    a supported dtype.

    Parameters
    ----------
    subarr : np.ndarray[object]
    cast_numeric_deprecated : bool, default True
        Whether to issue a FutureWarning when inferring numeric dtypes.

    Returns
    -------
    np.ndarray or ExtensionArray
    Tzdatetime64[ns])convert_datetimeconvert_timedeltaconvert_periodconvert_intervaldtype_if_all_natr   zIn a future version, the Index constructor will not infer numeric dtypes when passed object-dtype sequences (matching Series behavior)r   )
r   rT  r   r   r$  r  r  r  r0   rs   )r7  r  r4  r   r   r   r)    s$   r)  indexestuple[Hashable, ...]c                  G  s6   dd | D }dd t | D }tdd |D }|S )z
    Return common name if all indices agree, otherwise None (level-by-level).

    Parameters
    ----------
    indexes : list of Index objects

    Returns
    -------
    list
        A list representing the unanimous 'names' found.
    c                 S  s   g | ]}t |jqS r   )r
  r  )r  r  r   r   r   r  E  s    z'get_unanimous_names.<locals>.<listcomp>c                 S  s   g | ]}h |qS r   r   r  nsr   r   r   r  F  r  c                 s  s(    | ]}t |d kr| ndV  qdS r=  )rd  r   r[  r   r   r   r  G  r  z&get_unanimous_names.<locals>.<genexpr>)r   r
  )rY  	name_tups	name_setsr  r   r   r   get_unanimous_names8  s   r_  r   c                 C  s   | j }t|r
|jS | S )z
    When checking if our dtype is comparable with another, we need
    to unpack CategoricalDtype to look at its categories.dtype.

    Parameters
    ----------
    other : Index

    Returns
    -------
    Index
    )r   r?   r  )r   r   r   r   r   r  K  s   r  c              
   C  s\   |d u r,zt | } W | S  ty+ } ztj| dtt d W Y d }~| S d }~ww | S )Nz3, sort order is undefined for incomparable objects.r   )r   	safe_sortr   r  r  RuntimeWarningr0   )r4  r   r  r   r   r   r  b  s   r  )r   r#   r   r#   )r   r   r   r   r   r9  r<  )rP  r    r   r   r   r   )rS  r   r   r   )r  r   r   r   r;  r:  )r7  r   r  r   r   r   )rY  r   r   rZ  )r   r   r   r   )
__future__r   r   r   	itertoolsr   r  typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   r  numpyr   pandas._configr   pandas._libsr   r   r  r   r   r   pandas._libs.join_libsr   r   pandas._libs.libr   r   pandas._libs.missingr   pandas._libs.tslibsr   r   r   r   r   pandas._typingr   r    r!   r"   r#   r$   r%   r&   r'   pandas.compat.numpyr(   r  pandas.errorsr)   r*   r+   pandas.util._decoratorsr,   r-   r.   r/   pandas.util._exceptionsr0   r1   pandas.core.dtypes.astyper2   pandas.core.dtypes.castr3   r4   r5   r6   r7   r8   r9   r:   pandas.core.dtypes.commonr;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   pandas.core.dtypes.concatrS   pandas.core.dtypes.dtypesrT   rU   rV   rW   rX   rY   pandas.core.dtypes.genericrZ   r[   r\   r]   r^   r_   r`   pandas.core.dtypes.inferencera   pandas.core.dtypes.missingrb   rc   rd   pandas.corere   rf   rg   pandas.core.accessorrh   pandas.core.algorithmscore
algorithmspandas.core.array_algos.putmaskri   rj   r  rk   rl   pandas.core.arrays.datetimesrm   rn   pandas.core.arrays.sparsero   pandas.core.arrays.string_rp   pandas.core.baserq   rr   pandas.core.commoncommonr&  pandas.core.constructionrs   rt   ru   pandas.core.indexersrv   pandas.core.indexes.frozenrw   pandas.core.opsrx   pandas.core.ops.invalidry   pandas.core.sortingrz   r{   r|   pandas.core.stringsr}   pandas.io.formats.printingr~   r   r   r   rC  r   r   r   r   r   __all__rA  _unsortable_typesr   rB  r   r   r   r   r(  r   r   r   r   r   rO  r0  r/  r  rP  r  _cast_depr_msgr)  r_  r  r  r   r   r   r   <module>   s
   <,(h
 $	


                                                       (;


	
)
