zmc
2023-12-22 9fdbf60165db0400c2e8e6be2dc6e88138ac719a
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
U
¬ý°d9Yã    @s\dZddlmZddlmZddlmZmZmZm    Z    m
Z
m Z m Z ddl ZddlmZmZmZddlmZddlmZmZmZmZmZmZmZdd    lmZmZm Z dd
l!m"Z"m#Z#dd l$m%Z%dd l&m'Z'erðdd l(m)Z)ddl*m+Z+ddl,m-Z-dddddddddœdd„Z.dddddœdd„Z/dd d!œd"d#„Z0ddd$œd%d&„Z1d'dd(d)œd*d+„Z2d'd'dd,dd(d-œd.d/„Z3djddd'd1œd2d3„Z4dkd5d6d'd7œd8d9„Z5dld5dd5d6d;d'd<œd=d>„Z6dmd?d5d@dAœdBdC„Z7dDdEdFdGœdHdI„Z8dndJdKdJdLœdMdN„Z9dod6dOœdPdQ„Z:d'dFdRdSdTdUœdVdW„Z;dXdYdZd[œd\d]„Z<dpd'd^d'd_œd`da„Z=dqdddbdcœddde„Z>dd'dfdgœdhdi„Z?dS)rz+ miscellaneous sorting / groupby utilities é)Ú annotations)Ú defaultdict)Ú TYPE_CHECKINGÚCallableÚ DefaultDictÚHashableÚIterableÚSequenceÚcastN)ÚalgosÚ    hashtableÚlib)Úunique_label_indices)ÚAxisIntÚ IndexKeyFuncÚLevelÚ
NaPositionÚShapeÚSortKindÚnpt)Ú ensure_int64Úensure_platform_intÚis_extension_array_dtype)Ú ABCMultiIndexÚ ABCRangeIndex)Úisna)Ú extract_array)Ú
MultiIndex)ÚExtensionArray©ÚIndexr zLevel | list[Level] | Nonezlist[bool] | boolrrÚboolrznpt.NDArray[np.intp] | None)ÚtargetÚlevelÚ    ascendingÚkindÚ na_positionÚsort_remainingÚkeyÚreturnc    Cs„t|||d}| ¡}|dk    r4|j|||d\}}nLt|tƒrRt| ¡||d}n.|r\|jsf|sj|jrjdSt    ||t
t |ƒ|d}|S)aU
    Helper method that return the indexer according to input parameters for
    the sort_index method of DataFrame and Series.
 
    Parameters
    ----------
    target : Index
    level : int or level name or list of ints or list of level names
    ascending : bool or list of bools, default True
    kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort'
    na_position : {'first', 'last'}, default 'last'
    sort_remaining : bool, default True
    key : callable, optional
 
    Returns
    -------
    Optional[ndarray[intp]]
        The indexer for the new index.
    )ÚlevelsN)r$r')Úordersr&)r%r$r&) Úensure_key_mappedZ_sort_levels_monotonicZ    sortlevelÚ
isinstancerÚlexsort_indexerZ_get_codes_for_sortingZis_monotonic_increasingZis_monotonic_decreasingÚnargsortr
r!)    r"r#r$r%r&r'r(Ú_Úindexer©r2úJd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/sorting.pyÚget_indexer_indexer4s6ÿ 
ÿ
ÿÿür4rznpt.NDArray[np.int64])ÚshapeÚsortÚxnullr)cCs|ddœdd„}ddœdd„}dd    „|Dƒ}t|ƒ}|sptt||ƒƒD]*\}\}}    |||    ƒ\}}    |||<|    ||<qDt|ƒ}||ƒ}
tj|d
|
…d d } | |d jd ddd} td
|
ƒD]8}||d krÔt d ¡} n | ||} | ||| 7} q¸|r,|d dk} |d
|
…D]}| |dkO} qd| | <|
t|ƒkr>qxt    | |d\}}|g||
d…}t|ƒg||
d…}qx| S)a{
    For the particular label_list, gets the offsets into the hypothetical list
    representing the totally ordered cartesian product of all possible label
    combinations, *as long as* this space fits within int64 bounds;
    otherwise, though group indices identify unique combinations of
    labels, they cannot be deconstructed.
    - If `sort`, rank of returned ids preserve lexical ranks of labels.
      i.e. returned id's can be used to do lexical sort on labels;
    - If `xnull` nulls (-1 labels) are passed through.
 
    Parameters
    ----------
    labels : sequence of arrays
        Integers identifying levels at each location
    shape : tuple[int, ...]
        Number of unique levels at each location
    sort : bool
        If the ranks of returned ids should match lexical ranks of labels
    xnull : bool
        If true nulls are excluded. i.e. -1 values in the labels are
        passed through.
 
    Returns
    -------
    An array of type int64 where two elements are equal if their corresponding
    labels are equal at all location.
 
    Notes
    -----
    The length of `labels` and `shape` must be identical.
    Úint)r)cSs<d}t|ƒD]&\}}|t|ƒ9}|tjks |Sq t|ƒS©Né)Ú    enumerater8r Úi8maxÚlen)r5ÚaccÚiÚmulr2r2r3Ú_int64_cut_offs  
 
z'get_group_index.<locals>._int64_cut_offztuple[np.ndarray, int]cSs$|dk ¡r|d|dfS||fS)Néÿÿÿÿr:©Úany)ÚlabÚsizer2r2r3Ú
maybe_lift˜sz#get_group_index.<locals>.maybe_liftcSsg|] }t|ƒ‘qSr2)r©Ú.0Úxr2r2r3Ú
<listcomp>sz#get_group_index.<locals>.<listcomp>r:Úi8©ZdtyperF©ZsubokÚcopyrB©r6N)
Úlistr;ÚzipÚnpÚprodÚastypeÚrangeÚint64r=Úcompress_group_index)Úlabelsr5r6r7rArGZlshaper?rErFZnlevZstrideÚoutÚmaskÚcomp_idsÚobs_idsr2r2r3Úget_group_indexms:#
    r^z2tuple[npt.NDArray[np.intp], npt.NDArray[np.int64]])Úsizesr)cCst||ddd}t|ddS)a¾
    Group_index is offsets into cartesian product of all possible labels. This
    space can be huge, so this function compresses it, by computing offsets
    (comp_ids) into the list of unique labels (obs_group_ids).
 
    Parameters
    ----------
    labels : list of label arrays
    sizes : tuple[int] of size of the levels
 
    Returns
    -------
    np.ndarray[np.intp]
        comp_ids
    np.ndarray[np.int64]
        obs_group_ids
    TF©r6r7rP)r^rX)rYr_Úidsr2r2r3Úget_compressed_idsËsrb)r5r)cCs$d}|D]}|t|ƒ9}q|tjkSr9)r8r r<)r5Zthe_prodrJr2r2r3Úis_int64_overflow_possibleãsrcznpt.NDArray[np.intp]zlist[npt.NDArray[np.intp]])Ú comp_labelsr5r)cCs’t|ƒrtdƒ‚g}d}t d¡}|}ttt|ƒƒƒD]L}||||||}t ||dkd¡| |¡||}|||9}q6|ddd…S)Nz,cannot deconstruct factorized group indices!r:rrB)    rcÚ
ValueErrorrSÚarrayÚreversedrVr=ÚputmaskÚappend)rdr5Ú
label_listZfactorÚyrJr?rYr2r2r3Ú_decons_group_indexës
 
rlz'Sequence[npt.NDArray[np.signedinteger]])r\r]r5rYr7r)csŠ|s:tjdd„|Dƒtjd}tj|tjd|}t|ƒ}t|ƒspt||ƒ}|sX| ¡s\|Sdd„t||ƒDƒSt    |ƒ‰‡fdd„|DƒS)a6
    Reconstruct labels from observed group ids.
 
    Parameters
    ----------
    comp_ids : np.ndarray[np.intp]
    obs_ids: np.ndarray[np.intp]
    shape : tuple[int]
    labels : Sequence[np.ndarray[np.signedinteger]]
    xnull : bool
        If nulls are excluded; i.e. -1 labels are passed through.
    css|]}|dk ¡VqdS)rBNrC)rIÚar2r2r3Ú    <genexpr>sz'decons_obs_group_ids.<locals>.<genexpr>rMcSsg|]\}}||‘qSr2r2)rIrJrkr2r2r3rKsz(decons_obs_group_ids.<locals>.<listcomp>cs"g|]}|ˆjtjddd‘qS)FTrN)rUrSÚintp©rIrE©r1r2r3rKs)
rSZfromiterroÚasarrayÚtuplercrlrDrRr)r\r]r5rYr7ZliftZ    arr_shaperZr2rqr3Údecons_obs_group_idss
$rtT)r5Úcompressr)cCsJt||ddd}|s(|jo | ¡d}nt|dd\}}t|ƒ}t||ƒS)NTFr`r:rP)r^rFÚmaxrXr=Úget_group_index_sorter)rYr5ruraÚngroupsZobsr2r2r3Úindexer_from_factorized"s ryÚlastÚstrzCallable | None)r&r(r)c sHddlm}g}g}t|tƒr.|gt|ƒ}n|dkrDdgt|ƒ}‡fdd„|Dƒ}t||ƒD]Ø\}}||dd}    |dkrŠtd    |›ƒ‚t|    jƒ}
|    j     ¡} |    jd
k} |rÖ|d krÄt
  | |
| ¡} n|d krÔ| d 7} n<|d kröt
  | |
|
| d ¡} n|d krt
  | d|
| ¡} |   ¡r$|
d 7}
|  |
¡|  | ¡q`t|t|ƒƒS)aL
    Performs lexical sorting on a set of keys
 
    Parameters
    ----------
    keys : sequence of arrays
        Sequence of ndarrays to be sorted by the indexer
    orders : bool or list of booleans, optional
        Determines the sorting order for each element in keys. If a list,
        it must be the same length as keys. This determines whether the
        corresponding element in keys should be sorted in ascending
        (True) or descending (False) order. if bool, applied to all
        elements as above. if None, defaults to True.
    na_position : {'first', 'last'}, default 'last'
        Determines placement of NA elements in the sorted list ("last" or "first")
    key : Callable, optional
        Callable key function applied to every element in keys before sorting
 
    Returns
    -------
    np.ndarray[np.intp]
    r)Ú CategoricalNTcsg|]}t|ˆƒ‘qSr2)r,)rIÚk©r(r2r3rKRsz#lexsort_indexer.<locals>.<listcomp>)Zordered)rzÚfirstúinvalid na_position: rBrzrr:)Úpandas.core.arraysr|r-r!r=rRreÚ
categoriesÚcodesrOrSÚwhererDriryrs) Úkeysr+r&r(r|rYr5r}ÚorderÚcatÚnrƒr[r2r~r3r.0s: 
 
 
 
 
 
 
 
 r.Ú    quicksortznpt.NDArray[np.bool_] | None)r%r$r&r(r[r)c CsB|dk    r&t||ƒ}t||||d|dSt|tƒr<|j|dSt|tƒsNt|ƒ}|dkrdt t    |ƒ¡}t
|ƒr||j|||dSt  |¡}t  t |ƒ¡}||}||}t |¡d}    |sÖ|ddd…}|ddd…}||j|d}
|sø|
ddd…}
|dkrt |
|    g¡}
n(|d    kr,t |    |
g¡}
ntd
|›ƒ‚t|
ƒS) a
    Intended to be a drop-in replacement for np.argsort which handles NaNs.
 
    Adds ascending, na_position, and key parameters.
 
    (GH #6399, #5231, #27237)
 
    Parameters
    ----------
    kind : str, default 'quicksort'
    ascending : bool, default True
    na_position : {'first', 'last'}, default 'last'
    key : Optional[Callable], default None
    mask : Optional[np.ndarray[bool]], default None
        Passed when called by ExtensionArray.argsort.
 
    Returns
    -------
    np.ndarray[np.intp]
    N)r%r$r&r(r[)r$)r$r%r&rrB©r%rzrr€)r,r/r-rÚargsortrrrSrrrrZ
asanyarrayÚaranger=ZnonzeroZ concatenaterer) Úitemsr%r$r&r(r[ÚidxÚnon_nansÚ non_nan_idxZnan_idxr1r2r2r3r/qsF
ú    
 
 
 
 
 
 
r/rr)ÚvaluesÚmethodÚaxiscsš|dks t‚|dkrtjntj‰t t|ƒ¡}| ¡}|jdkrŽ| ¡r‚|dkr\t    ||ƒ}nt    |j
|j
ƒ}t  ‡fdd„|Dƒ¡Sˆ||dSt ||ˆƒS)a
    Implementation of np.argmin/argmax but for ExtensionArray and which
    handles missing values.
 
    Parameters
    ----------
    values : ExtensionArray
    method : {"argmax", "argmin"}
    axis : int, default 0
 
    Returns
    -------
    int
    >ÚargminÚargmaxr•r:csg|]\}}t||ˆƒ‘qSr2)Ú _nanargminmax)rIÚvÚm©Úfuncr2r3rKÖsznargminmax.<locals>.<listcomp>)r“) ÚAssertionErrorrSr•r”rrrZ_values_for_argsortÚndimrDrRÚTrfr–)r‘r’r“r[Z
arr_valuesZzippedr2r™r3Ú
nargminmax»s 
  ržz
np.ndarrayznpt.NDArray[np.bool_]r8)r‘r[r)cCs0t |jd¡}||}||}|||ƒS)z#
    See nanargminmax.__doc__.
    r)rSrŒr5)r‘r[ršrŽrrr2r2r3r–Üs
 
r–rr)Úindexr(r)csn|dk    r6t|ttfƒr|g‰n|‰‡fdd„ˆDƒ‰nttˆjƒƒ‰‡‡‡fdd„tˆjƒDƒ}tˆƒ |¡S)ad
    Returns a new MultiIndex in which key has been applied
    to all levels specified in level (or all levels if level
    is None). Used for key sorting for MultiIndex.
 
    Parameters
    ----------
    index : MultiIndex
        Index to which to apply the key function on the
        specified levels.
    key : Callable
        Function that takes an Index and returns an Index of
        the same shape. This key is applied to each level
        separately. The name of the level can be used to
        distinguish different levels for application.
    level : list-like, int or str, default None
        Level or list of levels to apply the key function to.
        If None, key function is applied to all levels. Other
        levels are left unchanged.
 
    Returns
    -------
    labels : MultiIndex
        Resulting MultiIndex with modified levels.
    Ncsg|]}ˆ |¡‘qSr2)Z_get_level_number)rIZlev)rŸr2r3rK
sz1_ensure_key_mapped_multiindex.<locals>.<listcomp>cs.g|]&}|ˆkr tˆ |¡ˆƒnˆ |¡‘qSr2)r,Z_get_level_values)rIr#©rŸr(Z sort_levelsr2r3rKsþÿ)r-r{r8rQrVZnlevelsÚtypeZ from_arrays)rŸr(r#Zmappedr2r r3Ú_ensure_key_mapped_multiindexçsür¢r~c    Cs°ddlm}|s|St|tƒr,t|||dS|| ¡ƒ}t|ƒt|ƒkrPtdƒ‚z(t||ƒrf||ƒ}nt|ƒ}||ƒ}Wn2t    k
rªt    dt|ƒ›dt|ƒ›dƒ‚YnX|S)aÁ
    Applies a callable key function to the values function and checks
    that the resulting value has the same shape. Can be called on Index
    subclasses, Series, DataFrames, or ndarrays.
 
    Parameters
    ----------
    values : Series, DataFrame, Index subclass, or ndarray
    key : Optional[Callable], key to be called on the values array
    levels : Optional[List], if values is a MultiIndex, list of levels to
    apply the key to.
    rr)r#zDUser-provided `key` function must not change the shape of the array.z6User-provided `key` function returned an invalid type z-             which could not be converted to Ú.)
Zpandas.core.indexes.apir r-rr¢rOr=rer¡Ú    TypeError)r‘r(r*r ÚresultZtype_of_valuesr2r2r3r,s2 
 ÿÿ
  ÿÿ
r,zIterable[Index]zIterable[np.ndarray]z list[tuple])r\rxr*rYr)c    Cs†|jtjdd}ttƒ}t||ƒD]P\}}t |¡}| ||jtjdd¡t    |ƒD]}|| 
||  |¡¡qTq"dd„|  ¡DƒS)z%Map compressed group id -> key tuple.F)rOcSsg|] }t|ƒ‘qSr2)rs)rIrfr2r2r3rKRsz&get_flattened_list.<locals>.<listcomp>) rUrSrWrrQrRr ÚInt64HashTableZmap_keys_to_valuesrVriZget_itemr‘)    r\rxr*rYZarraysZlabsr#Útabler?r2r2r3Úget_flattened_listDs
 r¨zlist[np.ndarray]z list[Index]z$dict[Hashable, npt.NDArray[np.intp]])rjr…r)cs’tdd„|Dƒƒ}t||ddd}t |dk¡r4iSt|ƒrN|joH| ¡dn tj|dd}t||ƒ‰‡fd    d
„|Dƒ}|     ˆ¡}t
  ˆ|||¡S) zJ
    Returns
    -------
    dict:
        Labels mapped to indexers.
    css|]}t|ƒVqdS)N)r=rHr2r2r3rn^sz#get_indexer_dict.<locals>.<genexpr>Tr`rBr:rLrMcsg|]}| ˆ¡‘qSr2)Útakerp©Úsorterr2r3rKlsz$get_indexer_dict.<locals>.<listcomp>) rsr^rSÚallrcrFrvrTrwr©r Z indices_fast)rjr…r5Ú group_indexrxZ sorted_labelsr2rªr3Úget_indexer_dictUs    ÿ ý
 
r®z
int | None)r­rxr)cCst|dkrd| ¡}t|ƒ}d}d}|dkoD||||t |¡k}|r`t t|ƒ|¡\}}n |jdd}t|ƒS)a    
    algos.groupsort_indexer implements `counting sort` and it is at least
    O(ngroups), where
        ngroups = prod(shape)
        shape = map(len, keys)
    that is, linear in the number of combinations (cartesian product) of unique
    values of groupby keys. This can be huge when doing multi-key groupby.
    np.argsort(kind='mergesort') is O(count x log(count)) where count is the
    length of the data-frame;
    Both algorithms are `stable` sort and that is necessary for correctness of
    groupby operations. e.g. consider:
        df.groupby(key)[col].transform('first')
 
    Parameters
    ----------
    group_index : np.ndarray[np.intp]
        signed integer dtype
    ngroups : int or None, default None
 
    Returns
    -------
    np.ndarray[np.intp]
    Nr:ggð?rZ    mergesortrŠ)rvr=rSÚlogr Zgroupsort_indexerrr‹)r­rxÚcountÚalphaÚbetaZ do_groupsortr«r0r2r2r3rwvs "þ
 rwz3tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]])r­r6r)cCsVt|ƒ}t |¡}t|ƒ}| |¡\}}|rFt|ƒdkrFt||ƒ\}}t|ƒt|ƒfS)zß
    Group_index is offsets into cartesian product of all possible labels. This
    space can be huge, so this function compresses it, by computing offsets
    (comp_ids) into the list of unique labels (obs_group_ids).
    r)r=r r¦rZget_labels_groupbyÚ_reorder_by_uniques)r­r6Z    size_hintr§r\Z obs_group_idsr2r2r3rX¡s
rXz2tuple[npt.NDArray[np.int64], npt.NDArray[np.intp]])ÚuniquesrYr)cCsd| ¡}tjt|ƒtjd}| |t t|ƒ¡¡|dk}| |¡}t ||d¡| |¡}||fS)z±
    Parameters
    ----------
    uniques : np.ndarray[np.int64]
    labels : np.ndarray[np.intp]
 
    Returns
    -------
    np.ndarray[np.int64]
    np.ndarray[np.intp]
    rMrrB)    r‹rSÚemptyr=roÚputrŒr©rh)r´rYr«Zreverse_indexerr[r2r2r3r³·s
 
r³)T)NrzN)r‰TrzNN)r)N)N)N)T)@Ú__doc__Ú
__future__rÚ collectionsrÚtypingrrrrrr    r
ÚnumpyrSZ pandas._libsr r r Zpandas._libs.hashtablerZpandas._typingrrrrrrrZpandas.core.dtypes.commonrrrZpandas.core.dtypes.genericrrZpandas.core.dtypes.missingrZpandas.core.constructionrZpandasrrrZpandas.core.indexes.baser r4r^rbrcrlrtryr.r/ržr–r¢r,r¨r®rwrXr³r2r2r2r3Ú<module>sZ  $
 $
     9^"ÿÿCúJ! ÿ1,"ÿ,ÿ