zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
U
¬ý°d]Òã@sädZddlmZddlZddlmZddlmZmZm    Z    ddl
Z
ddl Z ddl mZmZmZmZddlmZmZmZmZmZmZddlmZdd    lmZdd
lmZm Z dd 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.m/Z/m0Z0m1Z1m2Z2dd l3m4Z4dd l5m6Z6m7Z7m8Z8ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?ddl@mAZAmBZBddlCmDZDddlEmFZGmHZHmIZIddlJmKZKerªddlmLZLmMZMddlNmOZOmPZPmQZQddlRmSZSmTZTdddœdd„ZUdddddœdd„ZVdd œd!d"„ZWejXejYejZej[ej\ej]ej^ej_ej`ejaejbejcejdejed#œZfdd$œd%d&„Zgdd'dœd(d)„Zhd*d+„Zidd,dœd-d.„Zjd„d/d0œd1d2„ZkeiZlddd3d4œd5d6„Zmd…dd8d9d:d/d;d<œd=d>„Zneed?ƒed@ƒedAƒdBd†d8d8d9dDdEœdFdG„ƒZod‡d8d8d8d8dHdIœdJdK„Zpdˆdd8d/dLdMœdNdO„Zqd‰ddQd3dRœdSdT„ZrdŠdd8d/ddMœdUdV„Zsd‹ddYd'd'd8d8dZd[œd\d]„ZtdŒd^d_d/d/d^d`œdadb„ZuddcdYd8ddœdedf„ZvdŽddhdidjdkdlœdmdn„ZwdodpdqdrdsdthZxdd,dYduœdvdw„Zydd8d8d8dxdyœdzd{„Zzdd œd|d}„Z{dddœd~d„Z|d€d€d€dœd‚dƒ„Z}dS)‘zl
Generic data algorithms. This module is experimental at the moment and not
intended for public consumption
é)Ú annotationsN)Údedent)Ú TYPE_CHECKINGÚLiteralÚcast)ÚalgosÚ    hashtableÚiNaTÚlib)Ú AnyArrayLikeÚ    ArrayLikeÚAxisIntÚDtypeObjÚ TakeIndexerÚnpt)Údoc)Úfind_stack_level)Ú'construct_1d_object_array_from_listlikeÚinfer_dtype_from_array)Úensure_float64Ú ensure_objectÚensure_platform_intÚ is_array_likeÚ is_bool_dtypeÚis_categorical_dtypeÚis_complex_dtypeÚis_extension_array_dtypeÚis_float_dtypeÚ
is_integerÚis_integer_dtypeÚ is_list_likeÚis_numeric_dtypeÚis_object_dtypeÚ    is_scalarÚis_signed_integer_dtypeÚneeds_i8_conversion)Ú concat_compat)ÚBaseMaskedDtypeÚExtensionDtypeÚ PandasDtype)ÚABCDatetimeArrayÚABCExtensionArrayÚABCIndexÚ ABCMultiIndexÚ    ABCSeriesÚABCTimedeltaArray)ÚisnaÚna_value_for_dtype)Útake_nd)ÚarrayÚensure_wrapped_if_datetimelikeÚ extract_array)Úvalidate_indices)Ú NumpySorterÚNumpyValueArrayLike)Ú CategoricalÚIndexÚSeries)ÚBaseMaskedArrayÚExtensionArrayr z
np.ndarray)ÚvaluesÚreturncCsDt|tƒst|dd}t|jƒr.tt |¡ƒSt|jtƒr^t    d|ƒ}|j
sTt |j ƒSt |¡St |jƒrxt    d|ƒ}|jSt|jƒr´t|tjƒržt |¡ d¡St |¡jdddSnzt|jƒrÈt |¡St|jƒrð|jjdkræt|ƒSt |¡St|jƒrt    tj|ƒSt|jƒr.| d    ¡}t    tj|ƒ}|Stj|td
}t|ƒS) a„
    routine to ensure that our data is of the correct
    input dtype for lower-level routines
 
    This will coerce:
    - ints -> int64
    - uint -> uint64
    - bool -> uint8
    - datetimelike -> i8
    - datetime64tz -> i8 (in local tz)
    - categorical -> codes
 
    Parameters
    ----------
    values : np.ndarray or ExtensionArray
 
    Returns
    -------
    np.ndarray
    T©Ú extract_numpyr<r9Úuint8F©Úcopy)éé éÚi8©Údtype)Ú
isinstancer-r5r"rJrÚnpÚasarrayr'rZ_hasnaÚ _ensure_dataÚ_datarÚcodesrÚndarrayÚviewÚastyperrÚitemsizerrr%Úobject)r>Znpvalues©rVúMd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/algorithms.pyrNis<
 
 
 
 
 
 
 
 
 
 
 
 
 rNrr )r>rJÚoriginalr?cCsNt|tƒr|j|kr|St|tjƒs<| ¡}|j||d}n|j|dd}|S)zç
    reverse of _ensure_data
 
    Parameters
    ----------
    values : np.ndarray or ExtensionArray
    dtype : np.dtype or ExtensionDtype
    original : AnyArrayLike
 
    Returns
    -------
    ExtensionArray or np.ndarray
    rIFrC)rKr+rJrLZconstruct_array_typeZ_from_sequencerS)r>rJrXÚclsrVrVrWÚ_reconstruct_data·s rZ)r?cCsHt|ƒsDtj|dd}|dkr:t|tƒr0t|ƒ}t|ƒ}n
t |¡}|S)z5
    ensure that we are arraylike if not already
    F©Zskipna)ÚmixedÚstringú mixed-integer)    rr
Ú infer_dtyperKÚtupleÚlistrrLrM)r>ÚinferredrVrVrWÚ_ensure_arraylikeØs
 
 
rc)Z
complex128Z    complex64Úfloat64Úfloat32Zuint64Zuint32Zuint16rBÚint64Úint32Úint16Úint8r]rU©r>cCs t|ƒ}t|ƒ}t|}||fS)z‰
    Parameters
    ----------
    values : np.ndarray
 
    Returns
    -------
    htable : HashTable subclass
    values : ndarray
    )rNÚ_check_object_for_stringsÚ _hashtables)r>ÚndtyperrVrVrWÚ_get_hashtable_algoús rnÚstrcCs*|jj}|dkr&tj|dddkr&d}|S)z 
    Check if we can use string hashtable instead of object hashtable.
 
    Parameters
    ----------
    values : ndarray
 
    Returns
    -------
    str
    rUFr[)r]r])rJÚnamer
r_)r>rmrVrVrWrk s
rkcCst|ƒS)a
 
    Return unique values based on a hash table.
 
    Uniques are returned in order of appearance. This does NOT sort.
 
    Significantly faster than numpy.unique for long enough sequences.
    Includes NA values.
 
    Parameters
    ----------
    values : 1d array-like
 
    Returns
    -------
    numpy.ndarray or ExtensionArray
 
        The return can be:
 
        * Index : when the input is an Index
        * Categorical : when the input is a Categorical dtype
        * ndarray : when the input is a Series/ndarray
 
        Return numpy.ndarray or ExtensionArray.
 
    See Also
    --------
    Index.unique : Return unique values from an Index.
    Series.unique : Return unique values of Series object.
 
    Examples
    --------
    >>> pd.unique(pd.Series([2, 1, 3, 3]))
    array([2, 1, 3])
 
    >>> pd.unique(pd.Series([2] + [1] * 5))
    array([2, 1])
 
    >>> pd.unique(pd.Series([pd.Timestamp("20160101"), pd.Timestamp("20160101")]))
    array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]')
 
    >>> pd.unique(
    ...     pd.Series(
    ...         [
    ...             pd.Timestamp("20160101", tz="US/Eastern"),
    ...             pd.Timestamp("20160101", tz="US/Eastern"),
    ...         ]
    ...     )
    ... )
    <DatetimeArray>
    ['2016-01-01 00:00:00-05:00']
    Length: 1, dtype: datetime64[ns, US/Eastern]
 
    >>> pd.unique(
    ...     pd.Index(
    ...         [
    ...             pd.Timestamp("20160101", tz="US/Eastern"),
    ...             pd.Timestamp("20160101", tz="US/Eastern"),
    ...         ]
    ...     )
    ... )
    DatetimeIndex(['2016-01-01 00:00:00-05:00'],
            dtype='datetime64[ns, US/Eastern]',
            freq=None)
 
    >>> pd.unique(list("baabc"))
    array(['b', 'a', 'c'], dtype=object)
 
    An unordered Categorical will return categories in the
    order of appearance.
 
    >>> pd.unique(pd.Series(pd.Categorical(list("baabc"))))
    ['b', 'a', 'c']
    Categories (3, object): ['a', 'b', 'c']
 
    >>> pd.unique(pd.Series(pd.Categorical(list("baabc"), categories=list("abc"))))
    ['b', 'a', 'c']
    Categories (3, object): ['a', 'b', 'c']
 
    An ordered Categorical preserves the category ordering.
 
    >>> pd.unique(
    ...     pd.Series(
    ...         pd.Categorical(list("baabc"), categories=list("abc"), ordered=True)
    ...     )
    ... )
    ['b', 'a', 'c']
    Categories (3, object): ['a' < 'b' < 'c']
 
    An array of tuples
 
    >>> pd.unique([("a", "b"), ("b", "a"), ("a", "c"), ("b", "a")])
    array([('a', 'b'), ('b', 'a'), ('a', 'c')], dtype=object)
    )Úunique_with_maskrjrVrVrWÚunique's^rrÚintcCs8t|ƒdkrdSt|ƒ}t | ¡ d¡¡dk ¡}|S)aH
    Return the number of unique values for integer array-likes.
 
    Significantly faster than pandas.unique for long enough sequences.
    No checks are done to ensure input is integral.
 
    Parameters
    ----------
    values : 1d array-like
 
    Returns
    -------
    int : The number of unique values in ``values``
    rÚintp)ÚlenrNrLZbincountZravelrSÚsum)r>ÚresultrVrVrWÚ nunique_intsˆs
 rxznpt.NDArray[np.bool_] | None©ÚmaskcCs˜t|ƒ}t|jƒr| ¡S|}t|ƒ\}}|t|ƒƒ}|dkrZ| |¡}t||j|ƒ}|S|j||d\}}t||j|ƒ}|dk    s†t‚|| d¡fSdS)z?See algorithms.unique for docs. Takes a mask for masked arrays.NryÚbool)    rcrrJrrrnrurZÚAssertionErrorrS)r>rzrXrÚtableÚuniquesrVrVrWrqŸs
 
 rqznpt.NDArray[np.bool_])Úcompsr>r?cCsÚt|ƒstdt|ƒj›dƒ‚t|ƒs<tdt|ƒj›dƒ‚t|ttttj    fƒs†t
|ƒ}t |ƒ}t |ƒdkrªt |ƒrªt|ƒsªt|ƒ}n$t|tƒrœt |¡}nt|ddd}t |ƒ}t|dd}t|tj    ƒsÔ| |¡St|jƒrìt|ƒ |¡St|jƒrt|jƒstj|jtdSt|jƒr0t|| t¡ƒSt|jtƒrTtt |¡t |¡ƒSt |ƒdkršt |ƒd    kršt|ƒsšt|ƒ  ¡r’d
d „}ntj!}n6t "|j|jgg¡}|j|d d }|j|d d }t#j$}|||ƒS)zÂ
    Compute the isin boolean array.
 
    Parameters
    ----------
    comps : array-like
    values : array-like
 
    Returns
    -------
    ndarray[bool]
        Same length as `comps`.
    zIonly list-like objects are allowed to be passed to isin(), you passed a [ú]rT)rAZ extract_ranger@rIi@BécSst t ||¡t |¡¡S)N)rLÚ
logical_orÚin1dÚisnan)ÚcÚvrVrVrWÚfszisin.<locals>.fFrC)%r Ú    TypeErrorÚtypeÚ__name__rKr,r.r+rLrQrarcrur!r$rr-r3r5Úisinr%rJÚpd_arrayr"ÚzerosÚshaper{rSrUr(rMr0ÚanyrƒZfind_common_typeÚhtableZismember)rr>Z orig_valuesZ comps_arrayr‡ÚcommonrVrVrWr‹ºs^ÿÿ
ÿþý
 
 
 
 
ÿ
þý
r‹Tr{z
int | NonerUz'tuple[npt.NDArray[np.intp], np.ndarray])r>Úuse_na_sentinelÚ    size_hintÚna_valuerzr?c
Csf|}|jjdkrt}t|ƒ\}}||p,t|ƒƒ}|j|d|||d\}}    t||j|ƒ}t|    ƒ}    |    |fS)a(
    Factorize a numpy array to codes and uniques.
 
    This doesn't do any coercion of types or unboxing before factorization.
 
    Parameters
    ----------
    values : ndarray
    use_na_sentinel : bool, default True
        If True, the sentinel -1 will be used for NaN values. If False,
        NaN values will be encoded as non-negative integers and will not drop the
        NaN from the uniques of the values.
    size_hint : int, optional
        Passed through to the hashtable's 'get_labels' method
    na_value : object, optional
        A value in `values` to consider missing. Note: only use this
        parameter when you know that you don't have any values pandas would
        consider missing in the array (NaN for float data, iNaT for
        datetimes, etc.).
    mask : ndarray[bool], optional
        If not None, the mask is used as indicator for missing values
        (True = missing, False = valid) instead of `na_value` or
        condition "val != val".
 
    Returns
    -------
    codes : ndarray[np.intp]
    uniques : ndarray
    )ÚmÚMéÿÿÿÿ)Z na_sentinelr”rzZ    ignore_na)rJÚkindr    rnruÚ    factorizerZr)
r>r’r“r”rzrXÚ
hash_klassr}r~rPrVrVrWÚfactorize_arrays$  û
    r›z    values : sequence
        A 1-D sequence. Sequences that aren't pandas objects are
        coerced to ndarrays before factorization.
    zt    sort : bool, default False
        Sort `uniques` and shuffle `codes` to maintain the
        relationship.
    zG    size_hint : int, optional
        Hint to the hashtable sizer.
    )r>Úsortr“Fz%tuple[np.ndarray, np.ndarray | Index])rœr’r“r?c    Cst|ttfƒr|j||dSt|ƒ}|}t|ttfƒrX|jdk    rX|j|d\}}||fSt|tj    ƒsv|j|d\}}nTt 
|¡}|s¸t |ƒr¸t |ƒ}|  ¡r¸t|jdd}t |||¡}t|||d\}}|rðt|ƒdkrðt|||d    dd
\}}t||j|ƒ}||fS) aé
    Encode the object as an enumerated type or categorical variable.
 
    This method is useful for obtaining a numeric representation of an
    array when all that matters is identifying distinct values. `factorize`
    is available as both a top-level function :func:`pandas.factorize`,
    and as a method :meth:`Series.factorize` and :meth:`Index.factorize`.
 
    Parameters
    ----------
    {values}{sort}
    use_na_sentinel : bool, default True
        If True, the sentinel -1 will be used for NaN values. If False,
        NaN values will be encoded as non-negative integers and will not drop the
        NaN from the uniques of the values.
 
        .. versionadded:: 1.5.0
    {size_hint}
    Returns
    -------
    codes : ndarray
        An integer ndarray that's an indexer into `uniques`.
        ``uniques.take(codes)`` will have the same values as `values`.
    uniques : ndarray, Index, or Categorical
        The unique valid values. When `values` is Categorical, `uniques`
        is a Categorical. When `values` is some other pandas object, an
        `Index` is returned. Otherwise, a 1-D ndarray is returned.
 
        .. note::
 
           Even if there's a missing value in `values`, `uniques` will
           *not* contain an entry for it.
 
    See Also
    --------
    cut : Discretize continuous-valued array.
    unique : Find the unique value in an array.
 
    Notes
    -----
    Reference :ref:`the user guide <reshaping.factorize>` for more examples.
 
    Examples
    --------
    These examples all show factorize as a top-level method like
    ``pd.factorize(values)``. The results are identical for methods like
    :meth:`Series.factorize`.
 
    >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])
    >>> codes
    array([0, 0, 1, 2, 0])
    >>> uniques
    array(['b', 'a', 'c'], dtype=object)
 
    With ``sort=True``, the `uniques` will be sorted, and `codes` will be
    shuffled so that the relationship is the maintained.
 
    >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'], sort=True)
    >>> codes
    array([1, 1, 0, 2, 1])
    >>> uniques
    array(['a', 'b', 'c'], dtype=object)
 
    When ``use_na_sentinel=True`` (the default), missing values are indicated in
    the `codes` with the sentinel value ``-1`` and missing values are not
    included in `uniques`.
 
    >>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b'])
    >>> codes
    array([ 0, -1,  1,  2,  0])
    >>> uniques
    array(['b', 'a', 'c'], dtype=object)
 
    Thus far, we've only factorized lists (which are internally coerced to
    NumPy arrays). When factorizing pandas objects, the type of `uniques`
    will differ. For Categoricals, a `Categorical` is returned.
 
    >>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c'])
    >>> codes, uniques = pd.factorize(cat)
    >>> codes
    array([0, 0, 1])
    >>> uniques
    ['a', 'c']
    Categories (3, object): ['a', 'b', 'c']
 
    Notice that ``'b'`` is in ``uniques.categories``, despite not being
    present in ``cat.values``.
 
    For all other pandas objects, an Index of the appropriate type is
    returned.
 
    >>> cat = pd.Series(['a', 'a', 'c'])
    >>> codes, uniques = pd.factorize(cat)
    >>> codes
    array([0, 0, 1])
    >>> uniques
    Index(['a', 'c'], dtype='object')
 
    If NaN is in the values, and we want to include NaN in the uniques of the
    values, it can be achieved by setting ``use_na_sentinel=False``.
 
    >>> values = np.array([1, 2, 1, np.nan])
    >>> codes, uniques = pd.factorize(values)  # default: use_na_sentinel=True
    >>> codes
    array([ 0,  1,  0, -1])
    >>> uniques
    array([1., 2.])
 
    >>> codes, uniques = pd.factorize(values, use_na_sentinel=False)
    >>> codes
    array([0, 1, 0, 2])
    >>> uniques
    array([ 1.,  2., nan])
    )rœr’N)rœ)r’F)Úcompat)r’r“rT)r’Ú assume_uniqueÚverify)rKr,r.r™rcr*r/ÚfreqrLrQrMr"r0rr1rJÚwherer›ruÚ    safe_sortrZ)    r>rœr’r“rXrPr~Z    null_maskr”rVrVrWr™SsD ÿþ 
 ý
û
r™r;)rœÚ    ascendingÚ    normalizeÚdropnar?c
Csddlm}m}t|ddƒ}|r$dnd}    |dk    ròddlm}
||dd    }z|
||d
d } Wn,tk
r†} ztd ƒ| ‚W5d} ~ XYnX| j|d } |    | _| | j     
¡} | j      d¡| _    |   ¡} |rÞ| j dk ¡rÞ| jdd…} t t| ƒg¡}nt|ƒr@||dd    j j|d } |    | _|| j    _| j }t|tjƒsöt |¡}n¶t|tƒr†tt|jƒƒ}|||    dj||d ¡} |j| j    _| j }npt|ƒ}t||ƒ\}}|j tj!kr¶|  tj"¡}||ƒ}|j t#krà|j t$krà|  t$¡}||_||||    dd} |r| j%|d} |r| | &¡} | S)aK
    Compute a histogram of the counts of non-null values.
 
    Parameters
    ----------
    values : ndarray (1-d)
    sort : bool, default True
        Sort by values
    ascending : bool, default False
        Sort in ascending order
    normalize: bool, default False
        If True then compute a relative histogram
    bins : integer, optional
        Rather than count values, group them into half-open bins,
        convenience for pd.cut, only works with numeric data
    dropna : bool, default True
        Don't include counts of NaN
 
    Returns
    -------
    Series
    r)r:r;rpNZ
proportionÚcount)ÚcutFrCT)Zinclude_lowestz+bins argument only works with numeric data.©r¥Úinterval)Úindexrp)Úlevelr¥)rªrprD)r£)'Úpandasr:r;ÚgetattrZpandas.core.reshape.tiler§rˆÚ value_countsrprªZnotnarSZ
sort_indexÚ_valuesÚallZilocrLr3rurrKrQrMr-raÚrangeZnlevelsÚgroupbyÚsizeÚnamesrcÚvalue_counts_arraylikerJÚfloat16rer{rUZ sort_valuesrv)r>rœr£r¤Zbinsr¥r:r;Z
index_namerpr§ÚiiÚerrrwÚcountsÚlevelsÚkeysÚidxrVrVrWr®s`     
   ÿÿ
 
  r®z'tuple[ArrayLike, npt.NDArray[np.int64]])r>r¥rzr?cCs^|}t|ƒ}tj|||d\}}t|jƒrH|rH|tk}||||}}t||j|ƒ}||fS)zÓ
    Parameters
    ----------
    values : np.ndarray
    dropna : bool
    mask : np.ndarray[bool] or None, default None
 
    Returns
    -------
    uniques : np.ndarray
    counts : np.ndarray[np.int64]
    ry)rNrZ value_countr%rJr    rZ)r>r¥rzrXr»r¹Zres_keysrVrVrWrµ‹s
rµÚfirstz!Literal[('first', 'last', False)])r>Úkeepr?cCsJt|dƒr4t|jtƒr4td|ƒ}tj|j||jdSt    |ƒ}tj||dS)a
    Return boolean ndarray denoting duplicate values.
 
    Parameters
    ----------
    values : nd.array, ExtensionArray or Series
        Array over which to check for duplicate values.
    keep : {'first', 'last', False}, default 'first'
        - ``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
    -------
    duplicated : ndarray[bool]
    rJr<)r¾rz)r¾)
ÚhasattrrKrJr'rrÚ
duplicatedrOZ_maskrN)r>r¾rVrVrWrÀªs
 
rÀc
Cs¦t|ƒ}|}t|jƒr4t|ƒ}td|ƒ}|j|dSt|ƒ}tj|||d}zt     
|¡}Wn8t k
r’}zt j d|›tƒdW5d}~XYnXt||j|ƒ}|S)a
    Returns the mode(s) of an array.
 
    Parameters
    ----------
    values : array-like
        Array over which to check for duplicate values.
    dropna : bool, default True
        Don't consider counts of NaN/NaT.
 
    Returns
    -------
    np.ndarray or ExtensionArray
    r=r¨)r¥rzzUnable to sort modes: )Ú
stacklevelN)rcr%rJr4rÚ_moderNrÚmoderLrœrˆÚwarningsÚwarnrrZ)r>r¥rzrXZnpresultr¸rwrVrVrWrÃÇs"
 
 þrÃÚaverager¾r znpt.NDArray[np.float64])r>ÚaxisÚmethodÚ    na_optionr£Úpctr?c    Csdt|jƒ}t|ƒ}|jdkr4tj||||||d}n,|jdkrXtj|||||||d}ntdƒ‚|S)a÷
    Rank the values along a given axis.
 
    Parameters
    ----------
    values : np.ndarray or ExtensionArray
        Array whose values will be ranked. The number of dimensions in this
        array must not exceed 2.
    axis : int, default 0
        Axis over which to perform rankings.
    method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
        The method by which tiebreaks are broken during the ranking.
    na_option : {'keep', 'top'}, default 'keep'
        The method by which NaNs are placed in the ranking.
        - ``keep``: rank each NaN value with a NaN ranking
        - ``top``: replace each NaN with either +/- inf so that they
                   there are ranked at the top
    ascending : bool, default True
        Whether or not the elements should be ranked in ascending order.
    pct : bool, default False
        Whether or not to the display the returned rankings in integer form
        (e.g. 1, 2, 3) or in percentile form (e.g. 0.333..., 0.666..., 1).
    é)Úis_datetimelikeÚ ties_methodr£rÉrÊrE)rÇrÌrÍr£rÉrÊz&Array with ndim > 2 are not supported.)r%rJrNÚndimrZrank_1dZrank_2drˆ)r>rÇrÈrÉr£rÊrÌZranksrVrVrWÚrankðs.
 
ú
ù
rÏznpt.NDArray[np.int64]zint | npt.NDArray[np.int64])ÚarrÚbÚarr_maskÚb_maskr?c Csbt ||j¡}|dk    r&t ||j¡}nd}|dk    rJ|dk    rJt ||B¡}nB|dk    r^t |¡}n.|dk    rrt |¡}ntj|jtd}| d¡tj}t    }|dk}    |dk}
|     
¡sÄ|||k|@ 
¡} n`|
 
¡sâ|||k|@ 
¡} nB|||    ||    k||    @ 
¡p"|||
||
k||
@ 
¡} | r2t dƒ‚||} |dk    sN|dk    r^t  | |t    ¡| S)aÒ
    Perform array addition that checks for underflow and overflow.
 
    Performs the addition of an int64 array and an int64 integer (or array)
    but checks that they do not result in overflow first. For elements that
    are indicated to be NaN, whether or not there is overflow for that element
    is automatically ignored.
 
    Parameters
    ----------
    arr : np.ndarray[int64] addend.
    b : array or scalar addend.
    arr_mask : np.ndarray[bool] or None, default None
        array indicating which elements to exclude from checking
    b_mask : np.ndarray[bool] or None, default None
        array or scalar indicating which element(s) to exclude from checking
 
    Returns
    -------
    sum : An array for elements x + b for each element x in arr if b is
          a scalar or an array for elements x + y for each element pair
          (x, y) in (arr, b).
 
    Raises
    ------
    OverflowError if any x + y exceeds the maximum or minimum int64 value.
    NrITrzOverflow in int64 addition) rLZ broadcast_torŽZ logical_notÚemptyr{Úfillr
Úi8maxr    rÚ OverflowErrorÚputmask) rÐrÑrÒrÓZb2Zb2_maskZnot_nanrÖZi8minZmask1Zmask2Zto_raiserwrVrVrWÚchecked_add_with_arr+s:#  
    "ÿrÙr)ÚindicesrÇÚ
allow_fillcCs\t|ƒst |¡}tj|tjd}|rJt||j|ƒt|||d|d}n|j||d}|S)aÓ
    Take elements from an array.
 
    Parameters
    ----------
    arr : array-like or scalar value
        Non array-likes (sequences/scalars without a dtype) are coerced
        to an ndarray.
    indices : sequence of int or one-dimensional np.ndarray of int
        Indices to be taken.
    axis : int, default 0
        The axis over which to select values.
    allow_fill : bool, default False
        How to handle negative values in `indices`.
 
        * False: negative values in `indices` indicate positional indices
          from the right (the default). This is similar to :func:`numpy.take`.
 
        * True: negative values in `indices` indicate
          missing values. These values are set to `fill_value`. Any other
          negative values raise a ``ValueError``.
 
    fill_value : any, optional
        Fill value to use for NA-indices when `allow_fill` is True.
        This may be ``None``, in which case the default NA value for
        the type (``self.dtype.na_value``) is used.
 
        For multi-dimensional `arr`, each *element* is filled with
        `fill_value`.
 
    Returns
    -------
    ndarray or ExtensionArray
        Same type as the input.
 
    Raises
    ------
    IndexError
        When `indices` is out of bounds for the array.
    ValueError
        When the indexer contains negative values other than ``-1``
        and `allow_fill` is True.
 
    Notes
    -----
    When `allow_fill` is False, `indices` may be whatever dimensionality
    is accepted by NumPy for `arr`.
 
    When `allow_fill` is True, `indices` should be 1-D.
 
    See Also
    --------
    numpy.take : Take elements from an array along an axis.
 
    Examples
    --------
    >>> import pandas as pd
 
    With the default ``allow_fill=False``, negative numbers indicate
    positional indices from the right.
 
    >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1])
    array([10, 10, 30])
 
    Setting ``allow_fill=True`` will place `fill_value` in those positions.
 
    >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1], allow_fill=True)
    array([10., 10., nan])
 
    >>> pd.api.extensions.take(np.array([10, 20, 30]), [0, 0, -1], allow_fill=True,
    ...      fill_value=-10)
    array([ 10,  10, -10])
    rIT)rÇrÛÚ
fill_value)rÇ)rrLrMrtr6rŽr2Útake)rÐrÚrÇrÛrÜrwrVrVrWr݌sP
ÿrÝÚleftz$NumpyValueArrayLike | ExtensionArrayzLiteral[('left', 'right')]r7znpt.NDArray[np.intp] | np.intp)rÐÚvalueÚsideÚsorterr?cCsÒ|dk    rt|ƒ}t|tjƒrºt|jƒrºt|ƒs6t|ƒrºt |jj¡}t    |ƒrXt 
|g¡nt 
|¡}||j k  ¡r†||j k  ¡r†|j}n|j}t    |ƒr¦tt| |¡ƒ}qÂttt|ƒ|d}nt|ƒ}|j|||dS)aû
    Find indices where elements should be inserted to maintain order.
 
    Find the indices into a sorted array `arr` (a) such that, if the
    corresponding elements in `value` were inserted before the indices,
    the order of `arr` would be preserved.
 
    Assuming that `arr` is sorted:
 
    ======  ================================
    `side`  returned index `i` satisfies
    ======  ================================
    left    ``arr[i-1] < value <= self[i]``
    right   ``arr[i-1] <= value < self[i]``
    ======  ================================
 
    Parameters
    ----------
    arr: np.ndarray, ExtensionArray, Series
        Input array. If `sorter` is None, then it must be sorted in
        ascending order, otherwise `sorter` must be an array of indices
        that sort it.
    value : array-like or scalar
        Values to insert into `arr`.
    side : {'left', 'right'}, optional
        If 'left', the index of the first suitable location found is given.
        If 'right', return the last such index.  If there is no suitable
        index, return either 0 or N (where N is the length of `self`).
    sorter : 1-D array-like, optional
        Optional array of integer indices that sort array a into ascending
        order. They are typically the result of argsort.
 
    Returns
    -------
    array of ints or int
        If value is array-like, array of insertion points.
        If value is scalar, a single integer.
 
    See Also
    --------
    numpy.searchsorted : Similar method from NumPy.
    NrI)ràrá)rrKrLrQrrJrÚiinfor‰r#r3Úminr°ÚmaxrrsrŒr r4Ú searchsorted)rÐrßràrárâZ    value_arrrJrVrVrWråòs(0
ÿþýý    rårdrerfrgrhri)ÚnrÇcCsTt|ƒ}tj}|j}t|ƒ}|r(tj}ntj}t|t    ƒrF| 
¡}|j}t|tjƒs¬t |d|j ›dƒr˜|dkrˆt dt|ƒj ›d|›ƒ‚||| |¡ƒStt|ƒj ›dƒ‚d}t|jƒrÔtj}| d¡}t}d}n2|ràtj}n&t|ƒr|jjd    krtj}ntj}|j}|d
kr"| d d
¡}t |¡}tj|j|d }    td ƒgd}
|dkr^td |ƒnt|d ƒ|
|<||    t|
ƒ<|jjt krœt!j"||    |||dnŠtd ƒgd} |dkr¾t|d ƒntd |ƒ| |<t| ƒ} td ƒgd} |dkrøtd | ƒn
t| d ƒ| |<t| ƒ}||| ||ƒ|    | <|r6|     d¡}    |d
krP|    d d …df}    |    S)aQ
    difference of n between self,
    analogous to s-s.shift(n)
 
    Parameters
    ----------
    arr : ndarray or ExtensionArray
    n : int
        number of periods
    axis : {0, 1}
        axis to shift on
    stacklevel : int, default 3
        The stacklevel for the lost dtype warning.
 
    Returns
    -------
    shifted
    Ú__rz cannot diff z     on axis=zK has no 'diff' method. Convert to a suitable dtype prior to calling 'diff'.FrHT)rirhrËr—rINrE)Z datetimelikeztimedelta64[ns])#rsrLÚnanrJrÚoperatorÚxorÚsubrKr)Zto_numpyr¿rŠÚ
ValueErrorr‰Úshiftrˆr%rfrRr    Zobject_rrprerdrÎZreshaperÔrŽÚslicer`Ú _diff_specialrZdiff_2d)rÐrærÇÚnarJZis_boolÚopZ is_timedeltaZ    orig_ndimZout_arrZ
na_indexerZ _res_indexerZ res_indexerZ _lag_indexerZ lag_indexerrVrVrWÚdiffMsh
 ÿ
 
 
 
 
" "&
 
ròz.AnyArrayLike | tuple[AnyArrayLike, np.ndarray])r’ržrŸr?cCst|ƒstdƒ‚t|ƒs2t|ƒ\}}tj||d}d}t|ƒsZtj|dddkrZt    |ƒ}nRz| 
¡}|  |¡}Wn:tk
rª|j ržt |dtƒržt|ƒ}nt    |ƒ}YnX|dkr¸|St|ƒsÈtdƒ‚tt |¡ƒ}|sött|ƒƒt|ƒksötd    ƒ‚|dkr0t|ƒ\}    }|    t|ƒƒ}
|
 |¡t|
 |¡ƒ}|rt| 
¡} t| |d
d } |rn|t|ƒ k|t|ƒkB} nd} njtjt|ƒtjd}| |t t|ƒ¡¡|j |d d } |rÞ|d
k} |rÞ| |t|ƒ kB|t|ƒkB} |rü| dk    rüt | | d
¡|t| ƒfS)a
    Sort ``values`` and reorder corresponding ``codes``.
 
    ``values`` should be unique if ``codes`` is not None.
    Safe for use with mixed types (int, str), orders ints before strs.
 
    Parameters
    ----------
    values : list-like
        Sequence; must be unique if ``codes`` is not None.
    codes : list_like, optional
        Indices to ``values``. All out of bound indices are treated as
        "not found" and will be masked with ``-1``.
    use_na_sentinel : bool, default True
        If True, the sentinel -1 will be used for NaN values. If False,
        NaN values will be encoded as non-negative integers and will not drop the
        NaN from the uniques of the values.
    assume_unique : bool, default False
        When True, ``values`` are assumed to be unique, which can speed up
        the calculation. Ignored when ``codes`` is None.
    verify : bool, default True
        Check if codes are out of bound for the values and put out of bound
        codes equal to ``-1``. If ``verify=False``, it is assumed there
        are no out of bound codes. Ignored when ``codes`` is None.
 
    Returns
    -------
    ordered : AnyArrayLike
        Sorted ``values``
    new_codes : ndarray
        Reordered ``codes``; returned when ``codes`` is not None.
 
    Raises
    ------
    TypeError
        * If ``values`` is not list-like or if ``codes`` is neither None
        nor list-like
        * If ``values`` cannot be sorted
    ValueError
        * If ``codes`` is not None and ``values`` contain duplicates.
    zFOnly list-like objects are allowed to be passed to safe_sort as valuesrINFr[r^rzMOnly list-like objects or None are allowed to be passed to safe_sort as codesz,values should be unique if codes is not Noner—©rÜÚwrap)rÃ)r rˆrrrLrMrr
r_Ú _sort_mixedÚargsortrÝr³rKr`Ú _sort_tuplesrrurrrìrnZ map_locationsÚlookupr2rÔÚint_ÚputZarangerØ)r>rPr’ržrŸrJÚ_ráZorderedršÚtZorder2Z    new_codesrzZreverse_indexerrVrVrWr¢¾sd0ÿ ÿþ
 
ÿ
 
r¢c
Cs¢tjdd„|Dƒtd}tjdd„|Dƒtd}||@}t ||¡}t ||¡}| ¡d |¡}| ¡d |¡}| ¡d}t |||g¡}    | |    ¡S)z3order ints before strings before nulls in 1d arrayscSsg|]}t|tƒ‘qSrV)rKro©Ú.0ÚxrVrVrWÚ
<listcomp>Csz_sort_mixed.<locals>.<listcomp>rIcSsg|] }t|ƒ‘qSrV)r0rýrVrVrWrDsr)rLr3r{röZnonzerorÝZ concatenate)
r>Zstr_posZnull_posÚnum_posZ str_argsortZ num_argsortZstr_locsZnum_locsZ    null_locsZlocsrVrVrWrõAs  rõcCs:ddlm}ddlm}||dƒ\}}||dd}||S)a
    Convert array of tuples (1d) to array of arrays (2d).
    We need to keep the columns separately as they contain different types and
    nans (can't use `np.sort` as it may fail when str and nan are mixed in a
    column as types cannot be compared).
    r)Ú    to_arrays)Úlexsort_indexerNT)Zorders)Z"pandas.core.internals.constructionrZpandas.core.sortingr)r>rrZarraysrûZindexerrVrVrWr÷Ps
   r÷zArrayLike | Index)ÚlvalsÚrvalsr?cCsÌddlm}t|dd}t|dd}|j|dd\}}t |j|j¡}|||jddd}t|t    ƒr|t|t    ƒr|| 
|¡  ¡}n8t|t ƒrŒ|j }t|t ƒrœ|j }t t||gƒƒ}t|ƒ}| |¡j}t ||¡S)aù
    Extracts the union from lvals and rvals with respect to duplicates and nans in
    both arrays.
 
    Parameters
    ----------
    lvals: np.ndarray or ExtensionArray
        left values which is ordered in front.
    rvals: np.ndarray or ExtensionArray
        right values ordered after lvals.
 
    Returns
    -------
    np.ndarray or ExtensionArray
        Containing the unsorted union of both arrays.
 
    Notes
    -----
    Caller is responsible for ensuring lvals.dtype == rvals.dtype.
    r)r;Fr¨rórs)rªrJrD)r¬r;r®ZalignrLÚmaximumr>rªrKr-Úappendrrr,r¯r&r4ZreindexÚrepeat)rrr;Zl_countZr_countZ final_countZ unique_valsZrepeatsrVrVrWÚunion_with_duplicates_s    
 
 r    )N)TNNN)FTN)TFFNT)N)r½)TN)rrÆr¾TF)NN)rFN)rÞN)r)NTFT)~Ú__doc__Ú
__future__rréÚtextwraprÚtypingrrrrÄÚnumpyrLZ pandas._libsrrrr    r
Zpandas._typingr r r rrrZpandas.util._decoratorsrZpandas.util._exceptionsrZpandas.core.dtypes.castrrZpandas.core.dtypes.commonrrrrrrrrrrrr r!r"r#r$r%Zpandas.core.dtypes.concatr&Zpandas.core.dtypes.dtypesr'r(r)Zpandas.core.dtypes.genericr*r+r,r-r.r/Zpandas.core.dtypes.missingr0r1Zpandas.core.array_algos.taker2Zpandas.core.constructionr3rŒr4r5Zpandas.core.indexersr6r7r8r¬r9r:r;Zpandas.core.arraysr<r=rNrZrcZComplex128HashTableZComplex64HashTableZFloat64HashTableZFloat32HashTableZUInt64HashTableZUInt32HashTableZUInt16HashTableZUInt8HashTableZInt64HashTableZInt32HashTableZInt16HashTableZ Int8HashTableZStringHashTableZPyObjectHashTablerlrnrkrrrxrqZunique1dr‹r›r™r®rµrÀrÃrÏrÙrÝrårïròr¢rõr÷r    rVrVrVrWÚ<module>sÚ     L        N!òa]û>ÿÿÿñü9úmÿ ÿÿ+ú>üdûiüXsû