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
U
¬ý°dlEã    @s€UddlmZddlZddlZddlmZddlZddlZ    ddl
m Z m Z m Z mZmZddlmZmZejejejejejdœejejejejejdœejejej dœej!de"iiZ#d    e$d
<d6d d dœdd„Z%d7dd dœdd„Z&dd dœdd„Z'dddœdd„Z(dddœdd„Z)dddœd d!„Z*d"d#„Z+dddœd$d%„Z,d8d&d'd(d)d*d+œd,d-„Z-d9d*d(d(d*d.œd/d0„Z.d:d1dd2d d3œd4d5„Z/dS);é)Ú annotationsN)ÚAny)ÚBufferÚColumnÚColumnNullTypeÚ    DataFrameÚ    DtypeKind)Ú ArrowCTypesÚ
Endianness)ééé é@)r rr zdict[DtypeKind, dict[int, Any]]Ú
_NP_DTYPESTÚboolz pd.DataFrame)Ú
allow_copyÚreturncCs2t|tjƒr|St|dƒs"tdƒ‚t|j|dƒS)a¯
    Build a ``pd.DataFrame`` from any DataFrame supporting the interchange protocol.
 
    Parameters
    ----------
    df : DataFrameXchg
        Object supporting the interchange protocol, i.e. `__dataframe__` method.
    allow_copy : bool, default: True
        Whether to allow copying the memory to perform the conversion
        (if false then zero-copy approach is requested).
 
    Returns
    -------
    pd.DataFrame
    Ú __dataframe__z#`df` does not support __dataframe__)r)Ú
isinstanceÚpdrÚhasattrÚ
ValueErrorÚ_from_dataframer©Údfr©rú]d:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/interchange/from_dataframe.pyÚfrom_dataframes
 
rÚ DataFrameXchgrcCs„g}| ¡D]}t|ƒ}| |¡q |s<t|ƒdkr<tdƒ‚t|ƒdkrR|d}ntj|dddd}|j dd¡}|dk    r€||_    |S)    až
    Build a ``pd.DataFrame`` from the DataFrame interchange object.
 
    Parameters
    ----------
    df : DataFrameXchg
        Object supporting the interchange protocol, i.e. `__dataframe__` method.
    allow_copy : bool, default: True
        Whether to allow copying the memory to perform the conversion
        (if false then zero-copy approach is requested).
 
    Returns
    -------
    pd.DataFrame
    ézHTo join chunks a copy is required which is forbidden by allow_copy=FalserTF)ZaxisZ ignore_indexÚcopyz pandas.indexN)
Z
get_chunksÚprotocol_df_chunk_to_pandasÚappendÚlenÚ RuntimeErrorrÚconcatÚmetadataÚgetÚindex)rrZ
pandas_dfsÚchunkÚ    pandas_dfZ    index_objrrrr7s  ÿ 
r)rrcCs i}g}| ¡D]â}t|tƒs.td|›dƒ‚||krFtd|›dƒ‚| |¡}|jd}|tjtjtj    tj
fkr„t |ƒ\||<}nd|tj kr t |ƒ\||<}nH|tjkr¼t|ƒ\||<}n,|tjkrØt|ƒ\||<}ntd|›dƒ‚| |¡qt |¡}||jd<|S)z¡
    Convert interchange protocol chunk to ``pd.DataFrame``.
 
    Parameters
    ----------
    df : DataFrameXchg
 
    Returns
    -------
    pd.DataFrame
    zColumn z is not a stringz is not uniquerz
Data type z not handled yetZ_INTERCHANGE_PROTOCOL_BUFFERS)Z column_namesrÚstrrZget_column_by_nameÚdtyperÚINTÚUINTÚFLOATÚBOOLÚprimitive_column_to_ndarrayZ CATEGORICALÚcategorical_column_to_seriesÚSTRINGÚstring_column_to_ndarrayZDATETIMEÚdatetime_column_to_ndarrayÚNotImplementedErrorr"rrÚattrs)rÚcolumnsÚbuffersÚnameÚcolr,Úbufr*rrrr!\s6 
 
 
ü
 
 
 
 
r!rztuple[np.ndarray, Any])r;rcCs@| ¡}|d\}}t|||j| ¡ƒ}t|||dƒ}||fS)aJ
    Convert a column holding one of the primitive dtypes to a NumPy array.
 
    A primitive type is one of: int, uint, float, bool.
 
    Parameters
    ----------
    col : Column
 
    Returns
    -------
    tuple
        Tuple of np.ndarray holding the data and the memory owner object
        that keeps the memory alive.
    ÚdataÚvalidity)Ú get_buffersÚbuffer_to_ndarrayÚoffsetÚsizeÚ    set_nulls)r;r9Ú    data_buffÚ
data_dtyper=rrrr1Šs
 r1ztuple[pd.Series, Any]c Cs¬|j}|dstdƒ‚|d}t|dƒr6t |j¡}ntdƒ‚| ¡}|d\}}t|||j|     ¡ƒ}||t
|ƒ}t j |||dd}    t   |    ¡}
t|
||d    ƒ}
|
|fS)
a
    Convert a column holding categorical data to a pandas Series.
 
    Parameters
    ----------
    col : Column
 
    Returns
    -------
    tuple
        Tuple of pd.Series holding the data and the memory owner object
        that keeps the memory alive.
    Z is_dictionaryz-Non-dictionary categoricals not supported yetÚ
categoriesÚ_colz}Interchanging categorical columns isn't supported yet, and our fallback of using the `col._col` attribute (a ndarray) failed.r=Z
is_ordered)rFZorderedr>)Zdescribe_categoricalr6rÚnpÚarrayrGr?r@rArBr#rZ CategoricalÚSeriesrC) r;Z categoricalZ
cat_columnrFr9Z
codes_buffZ codes_dtypeÚcodesÚvaluesÚcatr=rrrr2£s*
ÿ ÿ
r2cCs¤|j\}}|tjtjtjfkr,t|›dƒ‚| ¡}|dsDtdƒ‚|d\}}|ddks`t‚|dtj    tj
fksxt‚t j dtj tjf}t||d| ¡d    }|d\}}    t||    |j| ¡dd
}
d } |tjtjfkr|d sêtd ƒ‚|d \} } t| | |j| ¡ƒ} |dkr| } d g| ¡}t| ¡ƒD]\}| d k    rZ| |rZtj||<q4||
||
|d…}t|ƒ}|jdd}|||<q4tj|dd|fS)a
    Convert a column holding string data to a NumPy array.
 
    Parameters
    ----------
    col : Column
 
    Returns
    -------
    tuple
        Tuple of np.ndarray holding the data and the memory owner object
        that keeps the memory alive.
    z3 null kind is not yet supported for string columns.Úoffsetsz#String buffers must contain offsetsr=rr ér)rAÚlength)rPNr>z*Validity buffers cannot be empty for maskszutf-8)ÚencodingÚobject©r,)Ú describe_nullrÚ NON_NULLABLEÚ USE_BITMASKÚ USE_BYTEMASKr6r?ÚAssertionErrorr    r3Z LARGE_STRINGrr.ZUINT8r
ÚNATIVEr@rBrAÚrangerHÚnanÚbytesÚdecodeZasarray)r;Ú    null_kindÚ sentinel_valr9rDZprotocol_data_dtyperEr=Z offset_buffZ offset_dtyperNÚnull_posÚ
valid_buffÚ valid_dtypeZstr_listÚiZunitsZ    str_bytesÚstringrrrr4Òs^
ýÿ þ
ü 
ÿ 
 
  r4cCsÎt d|¡}|r\| d¡| d¡}}|dkr6tdƒ‚|dkrF|d7}| d|›d¡}|St d    |¡}|r¼| d¡}|d
kr–| tj¡d  d ¡}n"|d krª| d¡}ntd|›ƒ‚|Std|›ƒ‚dS)z4Parse datetime `format_str` to interpret the `data`.zts([smun]):(.*)rrOÚzTimezones are not supported yetÚsz datetime64[ú]ztd([Dm])ÚDi€Qz datetime64[s]Úmzdatetime64[ms]zDate unit is not supported: z DateTime kind is not supported: N)ÚreÚmatchÚgroupr6ÚastyperHÚuint64)Ú
format_strr=Ztimestamp_metaÚunitÚtzZ    date_metarrrÚparse_datetime_format_str+s&  
 rrc    Csx| ¡}|j\}}}}|d\}}t|tj|dttd|d›ƒtjf|j    | 
¡ƒ}t ||ƒ}t |||dƒ}||fS)a
    Convert a column holding DateTime data to a NumPy array.
 
    Parameters
    ----------
    col : Column
 
    Returns
    -------
    tuple
        Tuple of np.ndarray holding the data and the memory owner object
        that keeps the memory alive.
    r=rr.r>) r?r,r@rr.Úgetattrr    r
rYrArBrrrC)r;r9Ú_roÚdbufr,r=rrrr5Ls  ü÷
r5rztuple[DtypeKind, int, str, str]Úintz
int | Nonez
np.ndarray)Úbufferr,rArPrc CsÂ|\}}}}t |i¡ |d¡}|dkr8td|›dƒ‚tj |¡}t |j||dt     |¡¡}    |dkr¢|dk    s|t
dƒ‚tjj |    |j fd}
t |
||ddStjj |    |j |dfdSdS)    aÚ
    Build a NumPy array from the passed buffer.
 
    Parameters
    ----------
    buffer : Buffer
        Buffer to build a NumPy array from.
    dtype : tuple
        Data type of the buffer conforming protocol dtypes format.
    offset : int, default: 0
        Number of elements to offset from the start of the buffer.
    length : int, optional
        If the buffer is a bit-mask, specifies a number of bits to read
        from the buffer. Has no effect otherwise.
 
    Returns
    -------
    np.ndarray
 
    Notes
    -----
    The returned array doesn't own the memory. The caller of this function is
    responsible for keeping the memory owner object alive as long as
    the returned NumPy array is being used.
    NzConversion for ú is not yet supported.r rz1`length` must be specified for a bit-mask buffer.)Úshape)Úfirst_byte_offset)rr'r6rHZ    ctypeslibZas_ctypes_typeÚctypesÚcastÚptrÚPOINTERrXZas_arrayÚbufsizeÚbitmask_to_bool_ndarray) rwr,rArPÚkindZ    bit_widthrtZ column_dtypeZ ctypes_typeZ data_pointerZarrrrrr@ps"  ÿÿr@)ÚbitmaskÚ mask_lengthrzrc
Cs
|d}||d…}|d;}tj|td}|d}d}td||ƒ}t|ƒD]$}|d||>@rhd||<|d7}qLt||dƒD]:}    ||    d}tdƒD] }|d|>@r²d||<|d7}qšq‚t|ƒdkr|d}tt|ƒ|ƒD] }|d|>@rüd||<|d7}qä|S)a˜
    Convert bit-mask to a boolean NumPy array.
 
    Parameters
    ----------
    bitmask : np.ndarray[uint8]
        NumPy array of uint8 dtype representing the bitmask.
    mask_length : int
        Number of elements in the mask to interpret.
    first_byte_offset : int, default: 0
        Number of elements to offset from the start of the first byte.
 
    Returns
    -------
    np.ndarray[bool]
    r NrSrrTéÿÿÿÿ)rHÚzerosrÚminrZr#)
r‚rƒrzZ bytes_to_skipZ    bool_maskÚvalZmask_idxZbits_in_first_byteÚjrcrrrr€§s0  
 
r€znp.ndarray | pd.Seriesz5tuple[Buffer, tuple[DtypeKind, int, str, str]] | None)r=r;r>Úallow_modify_inplacec    Csè|j\}}d}|tjkr(t |¡|k}nj|tjtjfkrp|sDtdƒ‚|\}}t|||j    | 
¡ƒ}|dkr’|}n"|tj tj fkr‚nt d|›dƒ‚|dk    rät |¡rä|s°| ¡}z d||<Wn&tk
râ| t¡}d||<YnX|S)aÆ
    Set null values for the data according to the column null kind.
 
    Parameters
    ----------
    data : np.ndarray or pd.Series
        Data to set nulls in.
    col : Column
        Column object that describes the `data`.
    validity : tuple(Buffer, dtype) or None
        The return value of ``col.buffers()``. We do not access the ``col.buffers()``
        here to not take the ownership of the memory of buffer objects.
    allow_modify_inplace : bool, default: True
        Whether to modify the `data` inplace when zero-copy is possible (True) or always
        modify a copy of the `data` (False).
 
    Returns
    -------
    np.ndarray or pd.Series
        Data with the nulls being set.
    Nz/Expected to have a validity buffer for the maskrz
Null kind rx)rTrZ USE_SENTINELrrJrVrWrXr@rArBrUZUSE_NANr6rHÚanyr Ú    TypeErrorrmÚfloat)    r=r;r>r‰r^r_r`rarbrrrrCÝs,
 
 
rC)T)T)rN)r)T)0Ú
__future__rr{rjÚtypingrÚnumpyrHZpandasrZ*pandas.core.interchange.dataframe_protocolrrrrrrZpandas.core.interchange.utilsr    r
r-Zint8Úint16Úint32Úint64r.Zuint8Zuint16Zuint32rnr/Úfloat32Úfloat64r0rrÚ__annotations__rrr!r1r2r4rrr5r@r€rCrrrrÚ<module>s@   ü %./Y!'ü8ÿ:ü