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
U
¬ý°d§@ã@sÊdZddlmZddlmZmZddlZddlmZm    Z    m
Z
m Z Gdd„dej ƒZ Gdd    „d    ej ƒZGd
d „d ej ƒZGd d „d e ƒZGdd„de ƒZGdd„deƒZGdd„deƒZGdd„deƒZdS)zX
A verbatim copy (vendored) of the spec from https://github.com/data-apis/dataframe-api
é)Ú annotations)ÚABCÚabstractmethodN)ÚAnyÚIterableÚSequenceÚ    TypedDictc@s0eZdZdZdZdZdZdZdZdZ    dZ
d    Z d
S) ÚDlpackDeviceTypez3Integer enum for device type codes matching DLPack.ééééééé    é
N) Ú__name__Ú
__module__Ú __qualname__Ú__doc__ZCPUZCUDAZ
CPU_PINNEDZOPENCLZVULKANZMETALZVPIZROCM©rrúad:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\pandas/core/interchange/dataframe_protocol.pyr    sr    c@s,eZdZdZdZdZdZdZdZdZ    dZ
d    S)
Ú    DtypeKindað
    Integer enum for data types.
 
    Attributes
    ----------
    INT : int
        Matches to signed integer data type.
    UINT : int
        Matches to unsigned integer data type.
    FLOAT : int
        Matches to floating point data type.
    BOOL : int
        Matches to boolean data type.
    STRING : int
        Matches to string data type (UTF-8 encoded).
    DATETIME : int
        Matches to datetime data type.
    CATEGORICAL : int
        Matches to categorical data type.
    rr
r ééééN) rrrrÚINTÚUINTÚFLOATÚBOOLÚSTRINGZDATETIMEZ CATEGORICALrrrrr!src@s$eZdZdZdZdZdZdZdZdS)ÚColumnNullTypea¼
    Integer enum for null type representation.
 
    Attributes
    ----------
    NON_NULLABLE : int
        Non-nullable column.
    USE_NAN : int
        Use explicit float NaN value.
    USE_SENTINEL : int
        Sentinel value besides NaN/NaT.
    USE_BITMASK : int
        The bit is set/unset representing a null on a certain position.
    USE_BYTEMASK : int
        The byte is set/unset representing a null on a certain position.
    rr
r r r N)    rrrrZ NON_NULLABLEZUSE_NANZ USE_SENTINELZ USE_BITMASKZ USE_BYTEMASKrrrrr"@s r"c@s&eZdZUded<ded<ded<dS)Ú ColumnBuffersztuple[Buffer, Any]Údataztuple[Buffer, Any] | NoneZvalidityÚoffsetsN©rrrÚ__annotations__rrrrr#Ys
r#c@s&eZdZUded<ded<ded<dS)ÚCategoricalDescriptionÚboolZ
is_orderedZ is_dictionaryz Column | NoneÚ
categoriesNr&rrrrr(js
r(c@sZeZdZdZeeddœdd„ƒƒZeeddœdd„ƒƒZedd    „ƒZed
dœd d „ƒZ    d S)ÚBufferaY
    Data in the buffer is guaranteed to be contiguous in memory.
 
    Note that there is no dtype attribute present, a buffer can be thought of
    as simply a block of memory. However, if the column that the buffer is
    attached to has a dtype that's supported by DLPack and ``__dlpack__`` is
    implemented, then that dtype information will be contained in the return
    value from ``__dlpack__``.
 
    This distinction is useful to support both data exchange via DLPack on a
    buffer and (b) dtypes like variable-length strings which do not have a
    fixed number of bytes per element.
    Úint©ÚreturncCsdS)z'
        Buffer size in bytes.
        Nr©ÚselfrrrÚbufsizeƒszBuffer.bufsizecCsdS)z?
        Pointer to start of the buffer as an integer.
        Nrr/rrrÚptrŠsz
Buffer.ptrcCs tdƒ‚dS)a~
        Produce DLPack capsule (see array API standard).
 
        Raises:
 
            - TypeError : if the buffer contains unsupported dtypes.
            - NotImplementedError : if DLPack support is not implemented
 
        Useful to have to connect to array libraries. Support optional because
        it's not completely trivial to implement for a Python-only library.
        Ú
__dlpack__N)ÚNotImplementedErrorr/rrrr3‘s zBuffer.__dlpack__z#tuple[DlpackDeviceType, int | None]cCsdS)zÆ
        Device type and device ID for where the data in the buffer resides.
        Uses device type codes matching DLPack.
        Note: must be implemented even if ``__dlpack__`` is not.
        Nrr/rrrÚ__dlpack_device__ szBuffer.__dlpack_device__N)
rrrrÚpropertyrr1r2r3r5rrrrr+ts
r+c@sàeZdZdZeddœdd„ƒZeeddœdd„ƒƒZeeddœd    d
„ƒƒZeed dœd d „ƒƒZ    eeddœdd„ƒƒZ
eeddœdd„ƒƒZ eeddœdd„ƒƒZ eddœdd„ƒZ ed!dddœdd„ƒZeddœdd „ƒZdS)"ÚColumna¦
    A column object, with only the methods and properties required by the
    interchange protocol defined.
 
    A column can contain one or more chunks. Each chunk can contain up to three
    buffers - a data buffer, a mask buffer (depending on null representation),
    and an offsets buffer (if variable-size binary; e.g., variable-length
    strings).
 
    TBD: Arrow has a separate "null" dtype, and has no separate mask concept.
         Instead, it seems to use "children" for both columns with a bit mask,
         and for nested dtypes. Unclear whether this is elegant or confusing.
         This design requires checking the null representation explicitly.
 
         The Arrow design requires checking:
         1. the ARROW_FLAG_NULLABLE (for sentinel values)
         2. if a column has two children, combined with one of those children
            having a null dtype.
 
         Making the mask concept explicit seems useful. One null dtype would
         not be enough to cover both bit and byte masks, so that would mean
         even more checking if we did it the Arrow way.
 
    TBD: there's also the "chunk" concept here, which is implicit in Arrow as
         multiple buffers per array (= column here). Semantically it may make
         sense to have both: chunks were meant for example for lazy evaluation
         of data which doesn't fit in memory, while multiple buffers per column
         could also come from doing a selection operation on a single
         contiguous buffer.
 
         Given these concepts, one would expect chunks to be all of the same
         size (say a 10,000 row dataframe could have 10 chunks of 1,000 rows),
         while multiple buffers could have data-dependent lengths. Not an issue
         in pandas if one column is backed by a single NumPy array, but in
         Arrow it seems possible.
         Are multiple chunks *and* multiple buffers per column necessary for
         the purposes of this interchange protocol, or must producers either
         reuse the chunk concept for this or copy the data?
 
    Note: this Column object can only be produced by ``__dataframe__``, so
          doesn't need its own version or ``__column__`` protocol.
    r,r-cCsdS)z³
        Size of the column, in elements.
 
        Corresponds to DataFrame.num_rows() if column is a single chunk;
        equal to size of this current chunk otherwise.
        Nrr/rrrÚsizeÕsz Column.sizecCsdS)zâ
        Offset of first element.
 
        May be > 0 if using chunks; for example for a column with N chunks of
        equal size M (only the last chunk may be shorter),
        ``offset = n * M``, ``n = 0 .. N-1``.
        Nrr/rrrÚoffsetÞsz Column.offsetztuple[DtypeKind, int, str, str]cCsdS)aú
        Dtype description as a tuple ``(kind, bit-width, format string, endianness)``.
 
        Bit-width : the number of bits as an integer
        Format string : data type description format string in Apache Arrow C
                        Data Interface format.
        Endianness : current only native endianness (``=``) is supported
 
        Notes:
            - Kind specifiers are aligned with DLPack where possible (hence the
              jump to 20, leave enough room for future extension)
            - Masks must be specified as boolean with either bit width 1 (for bit
              masks) or 8 (for byte masks).
            - Dtype width in bits was preferred over bytes
            - Endianness isn't too useful, but included now in case in the future
              we need to support non-native endianness
            - Went with Apache Arrow format strings over NumPy format strings
              because they're more complete from a dataframe perspective
            - Format strings are mostly useful for datetime specification, and
              for categoricals.
            - For categoricals, the format string describes the type of the
              categorical in the data buffer. In case of a separate encoding of
              the categorical (e.g. an integer to string mapping), this can
              be derived from ``self.describe_categorical``.
            - Data types not included: complex, Arrow-style null, binary, decimal,
              and nested (list, struct, map, union) dtypes.
        Nrr/rrrÚdtypeész Column.dtyper(cCsdS)a©
        If the dtype is categorical, there are two options:
        - There are only values in the data buffer.
        - There is a separate non-categorical Column encoding for categorical values.
 
        Raises TypeError if the dtype is not categorical
 
        Returns the dictionary with description on how to interpret the data buffer:
            - "is_ordered" : bool, whether the ordering of dictionary indices is
                             semantically meaningful.
            - "is_dictionary" : bool, whether a mapping of
                                categorical values to other objects exists
            - "categories" : Column representing the (implicit) mapping of indices to
                             category values (e.g. an array of cat1, cat2, ...).
                             None if not a dictionary-style categorical.
 
        TBD: are there any other in-memory representations that are needed?
        Nrr/rrrÚdescribe_categoricalszColumn.describe_categoricalztuple[ColumnNullType, Any]cCsdS)a7
        Return the missing value (or "null") representation the column dtype
        uses, as a tuple ``(kind, value)``.
 
        Value : if kind is "sentinel value", the actual value. If kind is a bit
        mask or a byte mask, the value (0 or 1) indicating a missing value. None
        otherwise.
        Nrr/rrrÚ describe_nullszColumn.describe_nullú
int | NonecCsdS)z€
        Number of null elements, if known.
 
        Note: Arrow uses -1 to indicate "unknown", but None seems cleaner.
        Nrr/rrrÚ
null_count*szColumn.null_countúdict[str, Any]cCsdS)zY
        The metadata for the column. See `DataFrame.metadata` for more details.
        Nrr/rrrÚmetadata3szColumn.metadatacCsdS)zE
        Return the number of chunks the column consists of.
        Nrr/rrrÚ
num_chunks:szColumn.num_chunksNúIterable[Column]©Ún_chunksr.cCsdS)zz
        Return an iterator yielding the chunks.
 
        See `DataFrame.get_chunks` for details on ``n_chunks``.
        Nr©r0rDrrrÚ
get_chunks@szColumn.get_chunksr#cCsdS)ab
        Return a dictionary containing the underlying buffers.
 
        The returned dictionary has the following contents:
 
            - "data": a two-element tuple whose first element is a buffer
                      containing the data and whose second element is the data
                      buffer's associated dtype.
            - "validity": a two-element tuple whose first element is a buffer
                          containing mask values indicating missing data and
                          whose second element is the mask value buffer's
                          associated dtype. None if the null representation is
                          not a bit or byte mask.
            - "offsets": a two-element tuple whose first element is a buffer
                         containing the offset values for variable-size binary
                         data (e.g., variable-length strings) and whose second
                         element is the offsets buffer's associated dtype. None
                         if the data buffer does not have an associated offsets
                         buffer.
        Nrr/rrrÚ get_buffersHszColumn.get_buffers)N)rrrrrr8r6r9r:r;r<r>r@rArFrGrrrrr7©s6+    
r7c@seZdZdZdZed0dddœdd„ƒZeed    d
œd d „ƒƒZed d
œdd„ƒZ    edd
œdd„ƒZ
ed d
œdd„ƒZ edd
œdd„ƒZ ed ddœdd„ƒZ edddœdd„ƒZed d
œd!d"„ƒZed#dd$œd%d&„ƒZed'dd(œd)d*„ƒZed1dd,d-œd.d/„ƒZd+S)2Ú    DataFramea2
    A data frame class, with only the methods required by the interchange
    protocol defined.
 
    A "data frame" represents an ordered collection of named columns.
    A column's "name" must be a unique string.
    Columns may be accessed by name or by position.
 
    This could be a public data frame class, or an object with the methods and
    attributes defined on this DataFrame class could be returned from the
    ``__dataframe__`` method of a public data frame class in a library adhering
    to the dataframe interchange protocol specification.
    rFTr))Ú nan_as_nullÚ
allow_copycCsdS)zHConstruct a new interchange object, potentially changing the parameters.Nr)r0rIrJrrrÚ __dataframe__yszDataFrame.__dataframe__r?r-cCsdS)a!
        The metadata for the data frame, as a dictionary with string keys. The
        contents of `metadata` may be anything, they are meant for a library
        to store information that it needs to, e.g., roundtrip losslessly or
        for two implementations to share data that is not (yet) part of the
        interchange protocol specification. For avoiding collisions with other
        entries, please add name the keys with the name of the library
        followed by a period and the desired name, e.g, ``pandas.indexcol``.
        Nrr/rrrr@}szDataFrame.metadatar,cCsdS)z@
        Return the number of columns in the DataFrame.
        Nrr/rrrÚ num_columnsŠszDataFrame.num_columnsr=cCsdS)zK
        Return the number of rows in the DataFrame, if available.
        Nrr/rrrÚnum_rowsszDataFrame.num_rowscCsdS)zH
        Return the number of chunks the DataFrame consists of.
        Nrr/rrrrA™szDataFrame.num_chunksz Iterable[str]cCsdS)z?
        Return an iterator yielding the column names.
        Nrr/rrrÚ column_namesŸszDataFrame.column_namesr7)Úir.cCsdS)z>
        Return the column at the indicated position.
        Nr)r0rOrrrÚ
get_column¥szDataFrame.get_columnÚstr)Únamer.cCsdS)zE
        Return the column whose name is the indicated name.
        Nr)r0rRrrrÚget_column_by_name«szDataFrame.get_column_by_namerBcCsdS)z:
        Return an iterator yielding the columns.
        Nrr/rrrÚ get_columns±szDataFrame.get_columnsz Sequence[int])Úindicesr.cCsdS)zS
        Create a new DataFrame by selecting a subset of columns by index.
        Nr)r0rUrrrÚselect_columns·szDataFrame.select_columnsz Sequence[str])Únamesr.cCsdS)zR
        Create a new DataFrame by selecting a subset of columns by name.
        Nr)r0rWrrrÚselect_columns_by_name½sz DataFrame.select_columns_by_nameNzIterable[DataFrame]rCcCsdS)a2
        Return an iterator yielding the chunks.
 
        By default (None), yields the chunks that the data is stored as by the
        producer. If given, ``n_chunks`` must be a multiple of
        ``self.num_chunks()``, meaning the producer must subdivide each chunk
        before yielding it.
        NrrErrrrFÃszDataFrame.get_chunks)FT)N)rrrrÚversionrrKr6r@rLrMrArNrPrSrTrVrXrFrrrrrHhs6 rH)rÚ
__future__rÚabcrrÚenumÚtypingrrrrÚIntEnumr    rr"r#r(r+r7rHrrrrÚ<module>s  
5@