1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
U
¬ý°dUWã@sŽdZddlmZddlmZmZmZddlZddl    m
Z
m Z ddl m Z ddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZdd    lmZdd
l m!Z!dd l"m#Z#m$Z$m%Z%m&Z&m'Z'dd l(m)Z)ddl*m+m,Z-d2dddddddœdd„Z.d3ddddœdd„Z/d4dddddddœdd„Z0dd„Z1d d!„Z2d"d#„Z3d5dddd$œd%d&„Z4d'd(„Z5dd)œd*d+„Z6dd,œd-d.„Z7ddd/œd0d1„Z8dS)6z,
Quantilization functions and related stuff
é)Ú annotations)ÚAnyÚCallableÚLiteralN)Ú    TimedeltaÚ    Timestamp)Ú infer_dtype)ÚIntervalLeftRight) Ú DT64NS_DTYPEÚensure_platform_intÚ is_bool_dtypeÚis_categorical_dtypeÚis_datetime64_dtypeÚis_datetime64tz_dtypeÚis_datetime_or_timedelta_dtypeÚis_extension_array_dtypeÚ
is_integerÚ is_list_likeÚis_numeric_dtypeÚ    is_scalarÚis_timedelta64_dtype)Ú    ABCSeries)Úisna)Ú CategoricalÚIndexÚ IntervalIndexÚ to_datetimeÚ to_timedelta)ÚnanopsTFéÚraiseÚboolÚintÚstr)ÚrightÚretbinsÚ    precisionÚinclude_lowestÚ
duplicatesÚorderedc     Cs|}    t|ƒ}t|ƒ\}}
t |¡sdt|ƒr<|dkr<tdƒ‚z
|j} Wn$tk
rjt |¡}|j} YnX| dkr|tdƒ‚t     
|¡t      |¡f} dd„| Dƒ\} }t  | ¡s¶t  |¡r¾tdƒ‚| |kr| | dkrÞdt | ƒnd8} ||dkrúdt |ƒnd7}tj| ||dd    d
}nJtj| ||dd    d
}|| d}|rR|d|8<n|d |7<nnt|tƒr‚|jrÒtd ƒ‚nPt|ƒrœtj|td }n
t |¡}t||
ƒ}t | d¡¡dk ¡rÒtdƒ‚t|||||||
||d    \}}t||||
|    ƒS)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).
 
        .. versionadded:: 1.1.0
 
    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$`bins` should be a positive integer.rzCannot cut empty arraycss|]}|dVqdS)gN©)Ú.0Úmir+r+úOd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/reshape/tile.pyÚ    <genexpr>szcut.<locals>.<genexpr>z?cannot specify integer `bins` when input data contains infinitygü©ñÒMbP?T)Zendpointéÿÿÿÿz*Overlapping IntervalIndex is not accepted.©ÚdtypeÚfloat64z!bins must increase monotonically.)r$Úlabelsr&r'r2r(r))Ú_preprocess_for_cutÚ_coerce_to_typeÚnpÚiterablerÚ
ValueErrorÚsizeÚAttributeErrorÚasarrayrZnanminZnanmaxÚisinfÚabsÚlinspaceÚ
isinstancerZis_overlappingrr
Ú_convert_bin_to_numeric_typeZdiffÚastypeÚanyÚ _bins_to_cutsÚ_postprocess_for_cut)ÚxÚbinsr$r4r%r&r'r(r)Úoriginalr2ÚszÚrngÚmnZmxZadjÚfacr+r+r.Úcut2sd@  
 
 ÿ
 
 
 
 
÷
rM)r%r&r(c     Cs†|}t|ƒ}t|ƒ\}}t|ƒr2t dd|d¡n|}t |¡}    |    t |    ¡}    t |    |¡}
t||
||d||d\} }
t    | |
|||ƒS)a!
    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])
    rr*T)r4r&r'r2r()
r5r6rr7r?r<ÚisnanZquantilerDrE) rFÚqr4r%r&r(rHr2Z    quantilesZx_nprGrLr+r+r.Úqcut4s"= 
 ù
 
rPz
np.ndarray)rGr$r&r'r(r)c    Csþ|s|dkrtdƒ‚|dkr$tdƒ‚t|tƒrP| |¡}    tj|    |dd}
|
|fSt |¡} t| ƒt|ƒkr–t|ƒdkr–|dkr’tdt    |ƒ›d    ƒ‚| }|ržd
nd } t
|j || d ƒ}    |rÎd |    t   |¡|dk<t|ƒ|    t|ƒkB|    dkB} |  ¡}|dk    rÌ|dkst|ƒstdƒ‚|dkr6t|||||d}nD|r\tt|ƒƒt|ƒkr\tdƒ‚nt|ƒt|ƒd krztdƒ‚t|ƒs¬t|tt|ƒƒt|ƒkr¢|nd|d}t  |    | d¡t ||    d ¡}
n*|    d }
|rö|
 t j¡}
t  |
| t j¡|
|fS)Nz.'labels' must be provided if 'ordered = False')r ZdropzHinvalid value for 'duplicates' parameter, valid options are: raise, dropT)Ú
categoriesr)ér zBin edges must be unique: z@.
You can drop duplicate edges by setting the 'duplicates' kwargÚleftr$)Úsider*rFzJBin labels must either be False, None or passed in as a list-like argument)r$r'r2zNlabels must be unique if ordered=True; pass ordered=False for duplicate labelsz9Bin labels must be one fewer than the number of bin edges)r9r@rZ get_indexerrZ
from_codesÚalgosÚuniqueÚlenÚreprr Z searchsortedr7r<rrCrÚ_format_labelsÚsetr ZputmaskZtake_ndrBr3Únan)rFrGr$r4r&r'r2r(r)ÚidsÚresultZ unique_binsrTZna_maskZhas_nasr+r+r.rDˆsr ÿ
 
 
ÿ 
ÿ
ÿÿÿ
ý rDcCsÆd}t|jƒr|j}n„t|jƒr>t|ƒjddd}t d¡}n\t|jƒr\t|ƒ}t d¡}n>t|jƒrt| tj    ¡}n&t
|jƒršt |jƒrš|j tj tjd}|dk    r¾t | ¡| tj    ¡tj¡}||fS)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údatetime64[ns]F©Úcopyztimedelta64[ns])r2Zna_value)rr2rrrBr7rrr Úint64rrZto_numpyr3r[ÚwhereZnotnaÚview)rFr2r+r+r.r6Ûs 
 
 
 
r6cCsˆt|dd}t|ƒr8|dkr.t|ƒ tj¡}q„tdƒ‚nLt|ƒsHt|ƒr„|dkr|t    |ƒ}t|ƒrn|j
ddd}| tj¡}ntdƒ‚|S)    a
    if the passed bin is of datetime/timedelta type,
    this method converts it to integer
 
    Parameters
    ----------
    bins : list-like of bins
    dtype : dtype of data
 
    Raises
    ------
    ValueError if bins are not of a compat dtype to dtype
    F)Zskipna)Ú    timedeltaZ timedelta64z!bins must be of timedelta64 dtype)ÚdatetimeZ
datetime64r^r_z bins must be of datetime64 dtype) rrrrcr7rar9rrrrB)rGr2Z
bins_dtyper+r+r.rAüs 
rAcCsFt|ƒr&t| tj¡dd |j¡}nt|ƒrBt| tj¡|d}|S)a/
    Convert bins to a DatetimeIndex or TimedeltaIndex if the original dtype is
    datelike
 
    Parameters
    ----------
    bins : list-like of bins
    dtype : dtype of data
 
    Returns
    -------
    bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is
           datelike
    T)Úutcr1)    rrrBr7raZ
tz_convertÚtzrr)rGr2r+r+r.Ú_convert_bin_to_datelike_types
rh)r&r$r'cs°|rdnd}tˆƒr*‡fdd„‰dd„}nNtˆƒr@t‰dd„}n8tˆƒrVt‰dd„}n"tˆ|ƒ‰‡fdd„‰‡fd    d„}‡fd
d „|Dƒ}|r¢|r¢||d ƒ|d <tj||d S)z%based on the dtype, return our labelsr$rScst|ˆjdS)N)rg)rrg©rFr1r+r.Ú<lambda>=óz _format_labels.<locals>.<lambda>cSs |tdƒS©NZ1ns©rrir+r+r.rj>rkcSs |tdƒSrlrmrir+r+r.rjArkcSs |tdƒSrlrmrir+r+r.rjDrkcs
t|ˆƒS)N©Ú _round_fracri©r&r+r.rjGrkcs|dˆ S)Né
r+rirpr+r.rjHrkcsg|] }ˆ|ƒ‘qSr+r+©r,Úb)Ú    formatterr+r.Ú
<listcomp>Jsz"_format_labels.<locals>.<listcomp>r)Úclosed)rrrrrÚ_infer_precisionrZ from_breaks)rGr&r$r'r2rvÚadjustZbreaksr+)r2rtr&r.rY4s"  
 
 
 
  rYcCs4t|ddƒ}|dkrt |¡}|jdkr0tdƒ‚|S)z‹
    handles preprocessing for cut where we convert passed
    input to array, strip the index information and store it
    separately
    ÚndimNr*z!Input array must be 1 dimensional)Úgetattrr7r<ryr9)rFryr+r+r.r5Rs  
 
r5)r%cCs8t|tƒr|j||j|jd}|s&|St||ƒ}||fS)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@rZ _constructorr{r|rh)rLrGr%r2rHr+r+r.rEcs 
 
rErpcCsdt |¡r|dkr|St |¡\}}|dkrPtt t t|ƒ¡¡ƒ d|}n|}t ||¡SdS)z7
    Round the fractional part of the given number
    rr*N)r7ÚisfiniteÚmodfr"ÚfloorÚlog10r>Zaround)rFr&ÚfracZwholeÚdigitsr+r+r.rots$ro)Úbase_precisionÚreturncs@t|dƒD]0‰‡fdd„|Dƒ}t |¡j|jkr
ˆSq
|S)z8
    Infer an appropriate precision for _round_frac
    écsg|]}t|ˆƒ‘qSr+rnrrrpr+r.ruˆsz$_infer_precision.<locals>.<listcomp>)ÚrangerUrVr:)rƒrGÚlevelsr+rpr.rwƒs
 
rw)TNFrFr T)NFrr )TNrFNr T)TFN)9Ú__doc__Ú
__future__rÚtypingrrrÚnumpyr7Z pandas._libsrrZpandas._libs.librZpandas._typingr    Zpandas.core.dtypes.commonr
r r r rrrrrrrrrZpandas.core.dtypes.genericrZpandas.core.dtypes.missingrZpandasrrrrrZ pandas.corerZpandas.core.algorithmsÚcoreZ
algorithmsrUrMrPrDr6rArhrYr5rErorwr+r+r+r.Ú<module>s\   <   ÷úW÷S!"ÿ