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
U
¬ý°dö@ã@sLdZddlmZddlmZmZddlZddlm    Z    ddl
m Z m Z m Z mZmZmZddlmZmZer€ddlmZdd    lmZd
d d œd d„Zd dœdd„Zdd dœdd„Zd dœdd„Zd dœdd„Zddddœdd„Zd7dd dd œd!d"„Zd8ddœd#d$„Zddœd%d&„Z d'd(„Z!d)d*dd+œd,d-„Z"d.d/œd0d1„Z#d2d3d3d4œd5d6„Z$dS)9z$
Low-dependency indexing utilities.
é)Ú annotations)Ú TYPE_CHECKINGÚAnyN)Ú AnyArrayLike)Ú is_array_likeÚ is_bool_dtypeÚis_extension_array_dtypeÚ
is_integerÚis_integer_dtypeÚ is_list_like)ÚABCIndexÚ    ABCSeries)Ú    DataFrame)ÚIndexÚsliceÚbool)ÚslcÚreturncCs&dd„}||jƒo$||jƒo$||jƒS)a(
    Check if a slice object can be interpreted as a positional indexer.
 
    Parameters
    ----------
    slc : slice
 
    Returns
    -------
    bool
 
    Notes
    -----
    A valid positional slice may also be interpreted as a label-based slice
    depending on the index being sliced.
    cSs|dkpt|ƒS©N©r    )Úval©rúQd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/indexers/utils.pyÚis_int_or_none6sz1is_valid_positional_slice.<locals>.is_int_or_none)ÚstartÚstopÚstep)rrrrrÚis_valid_positional_slice$s 
ÿýr)rcCs t|ƒot|tƒot|ƒtk     S)zœ
    Check if we have a list-like indexer that is *not* a NamedTuple.
 
    Parameters
    ----------
    key : object
 
    Returns
    -------
    bool
    )r Ú
isinstanceÚtupleÚtype)ÚkeyrrrÚis_list_like_indexer@s r"Úint)ÚndimrcCs@|dkrt|ƒrdSt|tƒr<t|ƒ|kr<tdd„|DƒƒSdS)zÓ
    Return True if we are all scalar indexers.
 
    Parameters
    ----------
    indexer : object
    ndim : int
        Number of dimensions in the object being indexed.
 
    Returns
    -------
    bool
    éTcss|]}t|ƒVqdSrr)Ú.0ÚxrrrÚ    <genexpr>bsz$is_scalar_indexer.<locals>.<genexpr>F)r    rrÚlenÚall)Úindexerr$rrrÚis_scalar_indexerPs
r,cCs6t|ƒrt|ƒsdSt|tƒs$|f}tdd„|DƒƒS)z‚
    Check if we have an empty indexer.
 
    Parameters
    ----------
    indexer : object
 
    Returns
    -------
    bool
    Tcss&|]}t|tjƒot|ƒdkVqdS)rN)rÚnpÚndarrayr))r&Úidxrrrr(vsz#is_empty_indexer.<locals>.<genexpr>)r r)rrÚany)r+rrrÚis_empty_indexerfs
 
r1cCsÎd}t|tjtfƒrˆt|ƒrÊt|ƒt|ƒkrz|jdkrzt|tƒrJt |¡}t|tjƒrr|jtj    krr| 
¡t|ƒkszt dƒ‚t|ƒsÊd}nBt|t ƒrÊt|ƒrÊt|ƒt ||ƒkr¾|jdkr¾t dƒ‚t|ƒsÊd}|S)aŠ
    Validate that value and indexer are the same length.
 
    An special-case is allowed for when the indexer is a boolean array
    and the number of true values equals the length of ``value``. In
    this case, no exception is raised.
 
    Parameters
    ----------
    indexer : sequence
        Key for the setitem.
    value : array-like
        Value for the setitem.
    values : array-like
        Values being set into.
 
    Returns
    -------
    bool
        Whether this is an empty listlike setting which is a no-op.
 
    Raises
    ------
    ValueError
        When the indexer is an ndarray or list and the lengths don't match.
    Fr%zKcannot set using a list-like indexer with a different length than the valueTzGcannot set using a slice indexer with a different length than the value)rr-r.Úlistr r)r$ÚarrayÚdtypeZbool_ÚsumÚ
ValueErrorrÚlength_of_indexer)r+ÚvalueÚvaluesZno_oprrrÚcheck_setitem_lengths}s4
 
 
ÿ
þýÿ
ÿr:z
np.ndarrayÚNone)ÚindicesÚnrcCsHt|ƒrD| ¡}|dkr,d|›d}t|ƒ‚| ¡}||krDtdƒ‚dS)a+
    Perform bounds-checking for an indexer.
 
    -1 is allowed for indicating missing values.
 
    Parameters
    ----------
    indices : ndarray
    n : int
        Length of the array being indexed.
 
    Raises
    ------
    ValueError
 
    Examples
    --------
    >>> validate_indices(np.array([1, 2]), 3) # OK
 
    >>> validate_indices(np.array([1, -2]), 3)
    Traceback (most recent call last):
        ...
    ValueError: negative dimensions are not allowed
 
    >>> validate_indices(np.array([1, 2, 3]), 3)
    Traceback (most recent call last):
        ...
    IndexError: indices are out-of-bounds
 
    >>> validate_indices(np.array([-1, -1]), 0) # OK
 
    >>> validate_indices(np.array([0, 1]), 0)
    Traceback (most recent call last):
        ...
    IndexError: indices are out-of-bounds
    éÿÿÿÿz-'indices' contains values less than allowed (z < -1)úindices are out-of-boundsN)r)Úminr6ÚmaxÚ
IndexError)r<r=Úmin_idxÚmsgZmax_idxrrrÚvalidate_indices½s% rET)r=ÚverifyrcCs€t|tƒr0t |¡}t|ƒdkr0tjdtjdS|dk}| ¡rX| ¡}|||7<|r|||k|dkB}| ¡r|t    dƒ‚|S)a&
    Attempt to convert indices into valid, positive indices.
 
    If we have negative indices, translate to positive here.
    If we have indices that are out-of-bounds, raise an IndexError.
 
    Parameters
    ----------
    indices : array-like
        Array of indices that we are to convert.
    n : int
        Number of elements in the array that we are indexing.
    verify : bool, default True
        Check that all entries are between 0 and n - 1, inclusive.
 
    Returns
    -------
    array-like
        An array-like of positive indices that correspond to the ones
        that were passed in initially to this function.
 
    Raises
    ------
    IndexError
        One of the converted indices either exceeded the number of,
        elements (specified by `n`), or was still negative.
    r©r4r?)
rr2r-r3r)ÚemptyÚintpr0ÚcopyrB)r<r=rFÚmaskrrrÚmaybe_convert_indicesñs
 
 rLcCs,|dk    r²t|tƒr²t|ƒ}|j}|j}|j}|dkr:d}n|dkrJ||7}|dksZ||kr`|}n|dkrp||7}|dkr~d}n |dkrž|d|d}}| }|||d|St|tttj    t
fƒrôt|t
ƒrÚt  |¡}|j t krì| ¡St|ƒSt|tƒr|j|j|jSt|ƒs dStdƒ‚dS)zX
    Return the expected length of target[indexer]
 
    Returns
    -------
    int
    Nrr%z%cannot find the length of the indexer)rrr)rrrr r r-r.r2r3r4rr5Úranger"ÚAssertionError)r+ÚtargetZ
target_lenrrrrrrr7$s<
 
 
 
r7cCst |¡dkrtdƒ‚dS)zú
    Helper function to disallow multi-dimensional indexing on 1D Series/Index.
 
    GH#27125 indexer like idx[:, None] expands dim, but we cannot do that
    and keep an index, so we used to return ndarray, which was deprecated
    in GH#30588.
    r%zzMulti-dimensional indexing (e.g. `obj[:, None]`) is no longer supported. Convert to a numpy array before indexing instead.N)r-r$r6)ÚresultrrrÚdisallow_ndim_indexingNsÿrQcCs8t|ƒdkr4t|dtƒr4t|tƒr,tdƒ‚|dS|S)z•
    If we have a length-1 tuple/list that contains a slice, unpack to just
    the slice.
 
    Notes
    -----
    The list case is deprecated.
    r%rzYIndexing with a single-item list containing a slice is not allowed. Pass a tuple instead.)r)rrr2r6)ÚtuprrrÚ unpack_1tuple]s    
ÿrSrr)Úcolumnsr8rcCsJ|jr"t|jƒt|ƒkrFtdƒ‚n$t| |¡dƒt|jƒkrFtdƒ‚dS)aÿ
    Checks if a key used as indexer has the same length as the columns it is
    associated with.
 
    Parameters
    ----------
    columns : Index The columns of the DataFrame to index.
    key : A list-like of keys to index with.
    value : DataFrame The value to set for the keys.
 
    Raises
    ------
    ValueError: If the length of key is not equal to the number of columns in value
                or if the number of columns referenced by key is not equal to number
                of columns.
    z"Columns must be same length as keyrN)Z    is_uniquer)rTr6Zget_indexer_non_unique)rTr!r8rrrÚcheck_key_lengthus
 
rUr©ÚitemcCs^t|ƒdkr>|dtkr&|dd…}n|dtkr>|dd…}t|ƒdkrRtdƒ‚|d}|S)z/
    Possibly unpack arr[..., n] to arr[n]
    r%rNr>ztoo many indices for array.)r)ÚEllipsisrBrVrrrÚunpack_tuple_and_ellipsess     rYrr)r3r+rc
Csddlm}t|ƒr$t|tƒr(|Sn|St|ƒsT||ƒ}t|ƒdkrTtjgtjd}|j    }t
|ƒr¶t |ƒrz|j t dd}ntj|t d}t|ƒt|ƒkr´tdt|ƒ›dt|ƒ›ƒ‚nXt|ƒrztj|tjd}Wn.tk
r}ztdƒ|‚W5d    }~XYnXntd
ƒ‚|S) aë
    Check if `indexer` is a valid array indexer for `array`.
 
    For a boolean mask, `array` and `indexer` are checked to have the same
    length. The dtype is validated, and if it is an integer or boolean
    ExtensionArray, it is checked if there are missing values present, and
    it is converted to the appropriate numpy array. Other dtypes will raise
    an error.
 
    Non-array indexers (integer, slice, Ellipsis, tuples, ..) are passed
    through as is.
 
    Parameters
    ----------
    array : array-like
        The array that is being indexed (only used for the length).
    indexer : array-like or list-like
        The array-like that's used to index. List-like input that is not yet
        a numpy array or an ExtensionArray is converted to one. Other input
        types are passed through as is.
 
    Returns
    -------
    numpy.ndarray
        The validated indexer as a numpy array that can be used to index.
 
    Raises
    ------
    IndexError
        When the lengths don't match.
    ValueError
        When `indexer` cannot be converted to a numpy ndarray to index
        (e.g. presence of missing values).
 
    See Also
    --------
    api.types.is_bool_dtype : Check if `key` is of boolean dtype.
 
    Examples
    --------
    When checking a boolean mask, a boolean ndarray is returned when the
    arguments are all valid.
 
    >>> mask = pd.array([True, False])
    >>> arr = pd.array([1, 2])
    >>> pd.api.indexers.check_array_indexer(arr, mask)
    array([ True, False])
 
    An IndexError is raised when the lengths don't match.
 
    >>> mask = pd.array([True, False, True])
    >>> pd.api.indexers.check_array_indexer(arr, mask)
    Traceback (most recent call last):
    ...
    IndexError: Boolean index has wrong length: 3 instead of 2.
 
    NA values in a boolean array are treated as False.
 
    >>> mask = pd.array([True, pd.NA])
    >>> pd.api.indexers.check_array_indexer(arr, mask)
    array([ True, False])
 
    A numpy boolean mask will get passed through (if the length is correct):
 
    >>> mask = np.array([True, False])
    >>> pd.api.indexers.check_array_indexer(arr, mask)
    array([ True, False])
 
    Similarly for integer indexers, an integer ndarray is returned when it is
    a valid indexer, otherwise an error is  (for integer indexers, a matching
    length is not required):
 
    >>> indexer = pd.array([0, 2], dtype="Int64")
    >>> arr = pd.array([1, 2, 3])
    >>> pd.api.indexers.check_array_indexer(arr, indexer)
    array([0, 2])
 
    >>> indexer = pd.array([0, pd.NA], dtype="Int64")
    >>> pd.api.indexers.check_array_indexer(arr, indexer)
    Traceback (most recent call last):
    ...
    ValueError: Cannot index with an integer indexer containing NA values
 
    For non-integer/boolean dtypes, an appropriate error is raised:
 
    >>> indexer = np.array([0., 2.], dtype="float64")
    >>> pd.api.indexers.check_array_indexer(arr, indexer)
    Traceback (most recent call last):
    ...
    IndexError: arrays used as indices must be of integer or boolean type
    r)r3rGF)r4Zna_valuez Boolean index has wrong length: z  instead of z9Cannot index with an integer indexer containing NA valuesNz9arrays used as indices must be of integer or boolean type)Zpandas.core.constructionr3r rrrr)r-rIr4rrZto_numpyrZasarrayrBr
r6)r3r+Zpd_arrayr4ÚerrrrrÚcheck_array_indexer¥s:\ 
 ÿ
ÿþr[)T)N)%Ú__doc__Ú
__future__rÚtypingrrÚnumpyr-Zpandas._typingrZpandas.core.dtypes.commonrrrr    r
r Zpandas.core.dtypes.genericr r Zpandas.core.framerZpandas.core.indexes.baserrr"r,r1r:rErLr7rQrSrUrYr[rrrrÚ<module>s,     @43*