
    MhU                       S r SSKJr  SSKJrJrJrJr  SSKr	SSK
JrJrJr  SSKJrJrJrJrJrJr  SSKJrJrJr  SSKJr  SS	KJr  SS
KJrJrJ r   SSK!J"s  J#r$  SSK%J&r&  \(       a  SSK'J(r(J)r)         S           SS jjr*    S     SS jjr+SS jr,      S             SS jjr-SS jr.S S jr/  S!       S"S jjr0S#S jr1S$S jr2S%S jr3S&S jr4g)'z,
Quantilization functions and related stuff
    )annotations)TYPE_CHECKINGAnyCallableLiteralN)	Timedelta	Timestamplib)ensure_platform_intis_bool_dtype
is_integeris_list_likeis_numeric_dtype	is_scalar)CategoricalDtypeDatetimeTZDtypeExtensionDtype)	ABCSeries)isna)CategoricalIndexIntervalIndex)dtype_to_unit)DtypeObjIntervalLeftRightc	                t   U n	[        U 5      n
[        U
5      u  p[        R                  " U5      (       d  [	        XU5      nOY[        U[        5      (       a  UR                  (       a  [        S5      eO'[        U5      nUR                  (       d  [        S5      e[        U
UUUUUUUS9u  p[        XXI5      $ )a  
Bin values into discrete intervals.

Use `cut` when you need to segment and sort data values into bins. This
function is also useful for going from a continuous variable to a
categorical variable. For example, `cut` could convert ages to groups of
age ranges. Supports binning into an equal number of bins, or a
pre-specified array of bins.

Parameters
----------
x : array-like
    The input array to be binned. Must be 1-dimensional.
bins : int, sequence of scalars, or IntervalIndex
    The criteria to bin by.

    * int : Defines the number of equal-width bins in the range of `x`. The
      range of `x` is extended by .1% on each side to include the minimum
      and maximum values of `x`.
    * sequence of scalars : Defines the bin edges allowing for non-uniform
      width. No extension of the range of `x` is done.
    * IntervalIndex : Defines the exact bins to be used. Note that
      IntervalIndex for `bins` must be non-overlapping.

right : bool, default True
    Indicates whether `bins` includes the rightmost edge or not. If
    ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]``
    indicate (1,2], (2,3], (3,4]. This argument is ignored when
    `bins` is an IntervalIndex.
labels : array or False, default None
    Specifies the labels for the returned bins. Must be the same length as
    the resulting bins. If False, returns only integer indicators of the
    bins. This affects the type of the output container (see below).
    This argument is ignored when `bins` is an IntervalIndex. If True,
    raises an error. When `ordered=False`, labels must be provided.
retbins : bool, default False
    Whether to return the bins or not. Useful when bins is provided
    as a scalar.
precision : int, default 3
    The precision at which to store and display the bins labels.
include_lowest : bool, default False
    Whether the first interval should be left-inclusive or not.
duplicates : {default 'raise', 'drop'}, optional
    If bin edges are not unique, raise ValueError or drop non-uniques.
ordered : bool, default True
    Whether the labels are ordered or not. Applies to returned types
    Categorical and Series (with Categorical dtype). If True,
    the resulting categorical will be ordered. If False, the resulting
    categorical will be unordered (labels must be provided).

Returns
-------
out : Categorical, Series, or ndarray
    An array-like object representing the respective bin for each value
    of `x`. The type depends on the value of `labels`.

    * None (default) : returns a Series for Series `x` or a
      Categorical for all other inputs. The values stored within
      are Interval dtype.

    * sequence of scalars : returns a Series for Series `x` or a
      Categorical for all other inputs. The values stored within
      are whatever the type in the sequence is.

    * False : returns an ndarray of integers.

bins : numpy.ndarray or IntervalIndex.
    The computed or specified bins. Only returned when `retbins=True`.
    For scalar or sequence `bins`, this is an ndarray with the computed
    bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For
    an IntervalIndex `bins`, this is equal to `bins`.

See Also
--------
qcut : Discretize variable into equal-sized buckets based on rank
    or based on sample quantiles.
Categorical : Array type for storing data that come from a
    fixed set of values.
Series : One-dimensional array with axis labels (including time series).
IntervalIndex : Immutable Index implementing an ordered, sliceable set.

Notes
-----
Any NA values will be NA in the result. Out of bounds values will be NA in
the resulting Series or Categorical object.

Reference :ref:`the user guide <reshaping.tile.cut>` for more examples.

Examples
--------
Discretize into three equal-sized bins.

>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
... # doctest: +ELLIPSIS
[(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...
Categories (3, interval[float64, right]): [(0.994, 3.0] < (3.0, 5.0] ...

>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)
... # doctest: +ELLIPSIS
([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...
Categories (3, interval[float64, right]): [(0.994, 3.0] < (3.0, 5.0] ...
array([0.994, 3.   , 5.   , 7.   ]))

Discovers the same bins, but assign them specific labels. Notice that
the returned Categorical's categories are `labels` and is ordered.

>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),
...        3, labels=["bad", "medium", "good"])
['bad', 'good', 'medium', 'medium', 'good', 'bad']
Categories (3, object): ['bad' < 'medium' < 'good']

``ordered=False`` will result in unordered categories when labels are passed.
This parameter can be used to allow non-unique labels:

>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3,
...        labels=["B", "A", "B"], ordered=False)
['B', 'B', 'A', 'A', 'B', 'B']
Categories (2, object): ['A', 'B']

``labels=False`` implies you just want the bins back.

>>> pd.cut([0, 1, 1, 2], bins=4, labels=False)
array([0, 1, 1, 3])

Passing a Series as an input returns a Series with categorical dtype:

>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),
...               index=['a', 'b', 'c', 'd', 'e'])
>>> pd.cut(s, 3)
... # doctest: +ELLIPSIS
a    (1.992, 4.667]
b    (1.992, 4.667]
c    (4.667, 7.333]
d     (7.333, 10.0]
e     (7.333, 10.0]
dtype: category
Categories (3, interval[float64, right]): [(1.992, 4.667] < (4.667, ...

Passing a Series as an input returns a Series with mapping value.
It is used to map numerically to intervals based on bins.

>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),
...               index=['a', 'b', 'c', 'd', 'e'])
>>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)
... # doctest: +ELLIPSIS
(a    1.0
 b    2.0
 c    3.0
 d    4.0
 e    NaN
 dtype: float64,
 array([ 0,  2,  4,  6,  8, 10]))

Use `drop` optional when bins is not unique

>>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,
...        right=False, duplicates='drop')
... # doctest: +ELLIPSIS
(a    1.0
 b    2.0
 c    3.0
 d    3.0
 e    NaN
 dtype: float64,
 array([ 0,  2,  4,  6, 10]))

Passing an IntervalIndex for `bins` results in those categories exactly.
Notice that values not covered by the IntervalIndex are set to NaN. 0
is to the left of the first bin (which is closed on the right), and 1.5
falls between two bins.

>>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])
>>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)
[NaN, (0.0, 1.0], NaN, (2.0, 3.0], (4.0, 5.0]]
Categories (3, interval[int64, right]): [(0, 1] < (2, 3] < (4, 5]]
z*Overlapping IntervalIndex is not accepted.z!bins must increase monotonically.)rightlabels	precisioninclude_lowest
duplicatesordered)_preprocess_for_cut_coerce_to_typenpiterable_nbins_to_bins
isinstancer   is_overlapping
ValueErrorr   is_monotonic_increasing_bins_to_cuts_postprocess_for_cut)xbinsr   r   retbinsr   r    r!   r"   originalx_idx_facs                J/var/www/html/env/lib/python3.13/site-packages/pandas/core/reshape/tile.pycutr6   4   s    z H"Eu%HE;;te51	D-	(	(IJJ  T{++@AA%	IC  7==    c           	     4   U n[        U 5      n[        U5      u  px[        U5      (       a  [        R                  " SSUS-   5      OUn	UR                  5       R                  5       R                  U	5      n
[        U[        U
5      UUSUS9u  p[        XX65      $ )am  
Quantile-based discretization function.

Discretize variable into equal-sized buckets based on rank or based
on sample quantiles. For example 1000 values for 10 quantiles would
produce a Categorical object indicating quantile membership for each data point.

Parameters
----------
x : 1d ndarray or Series
q : int or list-like of float
    Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
    array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles.
labels : array or False, default None
    Used as labels for the resulting bins. Must be of the same length as
    the resulting bins. If False, return only integer indicators of the
    bins. If True, raises an error.
retbins : bool, optional
    Whether to return the (bins, labels) or not. Can be useful if bins
    is given as a scalar.
precision : int, optional
    The precision at which to store and display the bins labels.
duplicates : {default 'raise', 'drop'}, optional
    If bin edges are not unique, raise ValueError or drop non-uniques.

Returns
-------
out : Categorical or Series or array of integers if labels is False
    The return type (Categorical or Series) depends on the input: a Series
    of type category if input is a Series else Categorical. Bins are
    represented as categories when categorical data is returned.
bins : ndarray of floats
    Returned only if `retbins` is True.

Notes
-----
Out of bounds values will be NA in the resulting Categorical object

Examples
--------
>>> pd.qcut(range(5), 4)
... # doctest: +ELLIPSIS
[(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]
Categories (4, interval[float64, right]): [(-0.001, 1.0] < (1.0, 2.0] ...

>>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"])
... # doctest: +SKIP
[good, good, medium, bad, bad]
Categories (3, object): [good < medium < bad]

>>> pd.qcut(range(5), 4, labels=False)
array([0, 0, 1, 2, 3])
r      T)r   r   r    r!   )r#   r$   r   r%   linspace	to_seriesdropnaquantiler,   r   r-   )r.   qr   r0   r   r!   r1   r2   r3   	quantilesr/   r4   s               r5   qcutr@     s    z H"Eu%HE,6qMMAq!a%(qI??##%..y9DdIC  7==r7   c                &   [        U5      (       a  US:  a  [        S5      eU R                  S:X  a  [        S5      eU R                  5       U R	                  5       4nUu  pE[        U R                  5      (       aA  [        R                  " U5      (       d  [        R                  " U5      (       a  [        S5      eXE:X  a  [        U R                  5      (       aR  [        U R                  5      n[        SS9R                  U5      nU R                  R                  XG-
  XW-   US-   SUS9nOXDS:w  a  S	[        U5      -  OS	-  nXUS:w  a  S	[        U5      -  OS	-  n[        R                   " XEUS-   S
S9nO[        U R                  5      (       a5  [        U R                  5      nU R                  R                  XEUS-   SUS9nO[        R                   " XEUS-   S
S9nXT-
  S	-  n	U(       a  US==   U	-  ss'   OUS==   U	-  ss'   [#        U5      $ )z`
If a user passed an integer N for bins, convert this to a sequence of N
equal(ish)-sized bins.
r9   z$`bins` should be a positive integer.r   zCannot cut empty arrayz?cannot specify integer `bins` when input data contains infinity)secondsN)startendperiodsfrequnitgMbP?T)endpoint)r   r*   sizeminmaxr   dtyper%   isinf_is_dt_or_tdr   r   as_unit_values_generate_rangeabsr:   r   )
r2   nbinsr   rngmnmxrG   tdr/   adjs
             r5   r'   r'   `  s   
 EAI?@@zzQ12299;		
$CFB$$"((2,,"((2,,M
 	
 
x$$ !-D1%--d3B ==00g27EAIDt 1 D 1W%#b'/%7B1W%#b'/%7B;;ruqy4@D$$
 !-D ==00%!)$T 1 D ;;ruqy4@Dw%GsNGHOH;r7   c                j   U(       d  Uc  [        S5      eUS;  a  [        S5      e[        U[        5      (       a3  UR                  U 5      n[	        USS9n	[
        R                  " XSS9n
X4$ [        R                  " U5      n[        U5      [        U5      :  a/  [        U5      S:w  a   US	:X  a  [        S
[        U5       S35      eUnU(       a  SOSn UR                  XS9n[        U5      nU(       a
  SXUS   :H  '   [!        U 5      U[        U5      :H  -  US:H  -  nUR#                  5       nUSLGa  Ub  [%        U5      (       d  [        S5      eUc  ['        XX%S9nOYU(       a,  [        [)        U5      5      [        U5      :w  a  [        S5      e[        U5      [        U5      S-
  :w  a  [        S5      e[        [+        USS 5      [        5      (       d.  [        U[        [)        U5      5      [        U5      :X  a  UOS US9n[,        R.                  " XS5        [        R0                  " X8S-
  5      n
X4$ US-
  n
U(       aD  U
R3                  [,        R4                  5      n
[,        R.                  " X[,        R6                  5        X4$ ! [         a  nU R                  R                  S:X  a  [        S5      UeU R                  R                  UR                  R                  s=:X  a  S:X  a  O  O[        S5      UeU R                  R                  S:X  a  [        S5      Uee S nAff = f)Nz.'labels' must be provided if 'ordered = False')raisedropzHinvalid value for 'duplicates' parameter, valid options are: raise, dropT)r"   F)rM   validate   r[   zBin edges must be unique: z@.
You can drop duplicate edges by setting the 'duplicates' kwargleftr   )sidemz!bins must be of timedelta64 dtypeMzHCannot use timezone-naive bins with timezone-aware values, or vice-versaz bins must be of datetime64 dtyper9   r   zJBin labels must either be False, None or passed in as a list-like argument)r   r    zNlabels must be unique if ordered=True; pass ordered=False for duplicate labelsz9Bin labels must be one fewer than the number of bin edgesrM   )
categoriesr"   )r*   r(   r   get_indexerr   r   
from_codesalgosuniquelenreprsearchsorted	TypeErrorrM   kindr   r   anyr   _format_labelssetgetattrr%   putmasktake_ndastypefloat64nan)r2   r/   r   r   r   r    r!   r"   ids	cat_dtyperesultunique_binsr`   errna_maskhas_nass                   r5   r,   r,     s    v~IJJ**V
 	
 $&&u%$T48	''uM|,,t$K
;#d)#D	Q ,T$ZL 9Q R  /4V'D1 c
"C !T!W5kSCI-.#(;GkkmGU,v"6"6% 
 >#uF S[)S[8' 
 6{c$i!m+ O  '&'48:JKK %(V%5V%D6$F 	

3#vQw/ < q]]2::.FJJv/<y   ;;s"@AsJ[[7C7   [[$?@cIs   J 
L2BL--L2c                   Sn[        U R                  5      (       a  U R                  nO[        U R                  5      (       a   U R                  [        R
                  5      n Op[        U R                  [        5      (       aQ  [        U R                  5      (       a7  U R                  [        R                  [        R                  S9n[        U5      n [        U 5      U4$ )z
if the passed data is of datetime/timedelta, bool or nullable int type,
this method converts it to numeric so that cut or qcut method can
handle it
N)rM   na_value)rO   rM   r   rs   r%   int64r(   r   r   to_numpyrt   ru   r   )r.   rM   x_arrs      r5   r$   r$     s     "EAGG	qww		HHRXX
 
AGG^	,	,1A!''1J1J

bff
=%L8U?r7   c                ^    [        U [        5      =(       d    [        R                  " U S5      $ )NmM)r(   r   r
   is_np_dtype)rM   s    r5   rO   rO     s!     e_-M1MMr7   c                  ^^	 U(       a  SOSn[        U R                  5      (       a  [        U R                  5      m	S nU	4S jnO[        TU 5      mU4S jnU4S jnU  Vs/ s H
  ou" U5      PM     nnU(       a  U(       a  U" US   5      US'   [        U R                  5      (       a   [	        U 5      " U5      R                  T	5      n[        R                  " XS9$ s  snf )	z%based on the dtype, return our labelsr   r_   c                    U $ N )r.   s    r5   <lambda> _format_labels.<locals>.<lambda>1  s    ar7   c                <   > U [        STS9R                  T5      -
  $ )Nr9   )rG   )r   rP   )r.   rG   s    r5   r   r   2  s    1y6>>tDDr7   c                   > [        U T5      $ r   )_round_fracr.   r   s    r5   r   r   5  s    k!Y7r7   c                   > U ST* -  -
  $ )N
   r   r   s    r5   r   r   6  s    1ryj11r7   r   )closed)rO   rM   r   _infer_precisiontyperP   r   from_breaks)
r/   r   r   r    r   	formatteradjustbbreaksrG   s
    `       @r5   rn   rn   "  s     ,1fF DJJ TZZ(	D$Y5	7	1$()DqilDF)6!9%q	DJJdF#++D1$$V;; *s   #C c                    [        U SS5      nUc  [        R                  " U 5      n U R                  S:w  a  [	        S5      e[        U 5      $ )z{
handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
separately
ndimNr9   z!Input array must be 1 dimensional)rp   r%   asarrayr   r*   r   )r.   r   s     r5   r#   r#   D  sD     1fd#D|JJqMvv{<==8Or7   c                   [        U[        5      (       a$  UR                  XR                  UR                  S9n U(       d  U $ [        U[
        5      (       a&  [        UR                  5      (       a  UR                  nX4$ )z
handles post processing for the cut method where
we combine the index information if the originally passed
datatype was a series
)indexname)	r(   r   _constructorr   r   r   r   rM   rQ   )r4   r/   r0   r1   s       r5   r-   r-   U  sc     (I&&##C~~HMM#R
$#3DJJ#?#?||9r7   c           	     <   [         R                  " U 5      (       a  U S:X  a  U $ [         R                  " U 5      u  p#US:X  aD  [        [         R                  " [         R
                  " [        U5      5      5      5      * S-
  U-   nOUn[         R                  " X5      $ )z/
Round the fractional part of the given number
r   r9   )r%   isfinitemodfintfloorlog10rS   around)r.   r   fracwholedigitss        r5   r   r   g  ss     ;;q>>Q!VggajA:"((288CI#67881<yHFFyy##r7   c           
         [        U S5       He  n[        R                  " U Vs/ s H  n[        X25      PM     sn5      n[        R
                  " U5      R                  UR                  :X  d  Mc  Us  $    U $ s  snf )z0
Infer an appropriate precision for _round_frac
   )ranger%   r   r   rf   rg   rJ   )base_precisionr/   r   r   levelss        r5   r   r   v  sf     >2.	E1[6EF<<$$		1 /  Fs   A8
)TNF   Fr[   T)r   boolr0   r   r   r   r    r   r!   strr"   r   )NFr   r[   )r0   r   r   r   r!   r   )r2   r   rT   r   r   r   returnr   )TNr   Fr[   T)r2   r   r/   r   r   r   r   r   r    r   r!   r   r"   r   )r.   r   r   ztuple[Index, DtypeObj | None])rM   r   r   r   )TF)r/   r   r   r   r   r   r    r   )r   r   )r0   r   )r   r   )r   r   r/   r   r   r   )5__doc__
__future__r   typingr   r   r   r   numpyr%   pandas._libsr   r	   r
   pandas.core.dtypes.commonr   r   r   r   r   r   pandas.core.dtypes.dtypesr   r   r   pandas.core.dtypes.genericr   pandas.core.dtypes.missingr   pandasr   r   r   pandas.core.algorithmscore
algorithmsrf   pandas.core.arrays.datetimeliker   pandas._typingr   r   r6   r@   r'   r,   r$   rO   rn   r#   r-   r   r   r   r7   r5   <module>r      s   #     
 1 + 
 ' & 9  X> X>
 X> X> X> X> X>| N> 	N>
 N> N>b:@  dd
d d
 d d d dN0N  	<
<< < 	<D"$$r7   