-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy patharrays.py
More file actions
484 lines (365 loc) · 12.7 KB
/
arrays.py
File metadata and controls
484 lines (365 loc) · 12.7 KB
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
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright the Vortex contributors
from __future__ import annotations
import abc
from collections.abc import Callable, Sequence
from typing import TYPE_CHECKING, Any
import pyarrow
from typing_extensions import override
import vortex._lib.arrays as _arrays # pyright: ignore[reportMissingModuleSource]
from vortex._lib.dtype import DType # pyright: ignore[reportMissingModuleSource]
from vortex._lib.serde import ( # pyright: ignore[reportMissingModuleSource]
ArrayContext,
SerializedArray,
decode_ipc_array_buffers,
)
try:
import pandas
except ImportError:
pass
else:
# HACK: monkey-patch a fixed implementation of the pd.ArrowDtype.type property accessor.
# See https://github.com/pandas-dev/pandas/issues/60068 for more details
_old_ArrowDtype_type: Callable[[pandas.ArrowDtype], type] = pandas.ArrowDtype.type.fget # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
@property
def __ArrowDtype_type_patched(self: pandas.ArrowDtype):
if pyarrow.types.is_string_view(self.pyarrow_dtype):
return str
if pyarrow.types.is_binary_view(self.pyarrow_dtype):
return bytes
assert _old_ArrowDtype_type is not None
return _old_ArrowDtype_type(self)
setattr(pandas.ArrowDtype, "type", __ArrowDtype_type_patched)
if TYPE_CHECKING:
import numpy
Array = _arrays.Array
def empty_arrow_table(schema: pyarrow.Schema) -> pyarrow.Table:
def empty_array(f: pyarrow.Field[pyarrow.DataType]) -> pyarrow.Array[pyarrow.Scalar[pyarrow.DataType]]:
return pyarrow.array([], type=f.type)
return pyarrow.Table.from_arrays([empty_array(field) for field in schema], schema=schema) # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType]
def arrow_table_from_struct_array(
array: pyarrow.StructArray | pyarrow.ChunkedArray[pyarrow.StructScalar],
) -> pyarrow.Table:
if len(array) == 0:
return empty_arrow_table(pyarrow.schema(array.type))
return pyarrow.Table.from_struct_array(array)
def _Array_to_arrow_table(self: _arrays.Array) -> pyarrow.Table:
"""Construct an Arrow table from this Vortex array.
.. seealso::
:meth:`.to_arrow_array`
Warning
-------
Only struct-typed arrays can be converted to Arrow tables.
Returns
-------
:class:`pyarrow.Table`
Examples
--------
>>> array = vortex.array([
... {'name': 'Joseph', 'age': 25},
... {'name': 'Narendra', 'age': 31},
... {'name': 'Angela', 'age': 33},
... {'name': 'Mikhail', 'age': 57},
... ])
>>> array.to_arrow_table()
pyarrow.Table
age: int64
name: string
----
age: [[25,31,33,57]]
name: [["Joseph","Narendra","Angela","Mikhail"]]
"""
array = self.to_arrow_array()
assert isinstance(array, pyarrow.StructArray | pyarrow.ChunkedArray)
return arrow_table_from_struct_array(array)
Array.to_arrow_table = _Array_to_arrow_table
def _Array_to_pandas(self: _arrays.Array) -> pandas.DataFrame:
"""Construct a Pandas dataframe from this Vortex array.
Warning
-------
Only struct-typed arrays can be converted to Pandas dataframes.
Returns
-------
:class:`pandas.DataFrame`
Examples
--------
Construct a dataframe from a Vortex array:
>>> array = vortex.array([
... {'name': 'Joseph', 'age': 25},
... {'name': 'Narendra', 'age': 31},
... {'name': 'Angela', 'age': 33},
... {'name': 'Mikhail', 'age': 57},
... ])
>>> array.to_pandas()
age name
0 25 Joseph
1 31 Narendra
2 33 Angela
3 57 Mikhail
"""
import pandas
return self.to_arrow_table().to_pandas(types_mapper=pandas.ArrowDtype) # pyright: ignore[reportUnknownMemberType]
Array.to_pandas = _Array_to_pandas
def _Array_to_polars_dataframe(
self: _arrays.Array,
): # -> 'polars.DataFrame': # breaks docs due to Polars issue #7027
"""Construct a Polars dataframe from this Vortex array.
.. seealso::
:meth:`.to_polars_series`
Warning
-------
Only struct-typed arrays can be converted to Polars dataframes.
Returns
-------
..
Polars excludes the DataFrame class from their Intersphinx index https://github.com/pola-rs/polars/issues/7027
`polars.DataFrame <https://docs.pola.rs/api/python/stable/reference/dataframe/index.html>`__
Examples
--------
>>> array = vortex.array([
... {'name': 'Joseph', 'age': 25},
... {'name': 'Narendra', 'age': 31},
... {'name': 'Angela', 'age': 33},
... {'name': 'Mikhail', 'age': 57},
... ])
>>> array.to_polars_dataframe()
shape: (4, 2)
┌─────┬──────────┐
│ age ┆ name │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════════╡
│ 25 ┆ Joseph │
│ 31 ┆ Narendra │
│ 33 ┆ Angela │
│ 57 ┆ Mikhail │
└─────┴──────────┘
"""
import polars
return polars.from_arrow(self.to_arrow_table()) # pyright: ignore[reportUnknownMemberType]
setattr(Array, "to_polars_dataframe", _Array_to_polars_dataframe)
def _Array_to_polars_series(self: _arrays.Array): # -> 'polars.Series': # breaks docs due to Polars issue #7027
"""Construct a Polars series from this Vortex array.
.. seealso::
:meth:`.to_polars_dataframe`
Returns
-------
..
Polars excludes the Series class from their Intersphinx index https://github.com/pola-rs/polars/issues/7027
`polars.Series <https://docs.pola.rs/api/python/stable/reference/series/index.html>`__
Examples
--------
Convert a numeric array with nulls to a Polars Series:
>>> vortex.array([1, None, 2, 3]).to_polars_series() # doctest: +NORMALIZE_WHITESPACE
shape: (4,)
Series: '' [i64]
[
1
null
2
3
]
Convert a UTF-8 string array to a Polars Series:
>>> vortex.array(['hello, ', 'is', 'it', 'me?']).to_polars_series() # doctest: +NORMALIZE_WHITESPACE
shape: (4,)
Series: '' [str]
[
"hello, "
"is"
"it"
"me?"
]
Convert a struct array to a Polars Series:
>>> array = vortex.array([
... {'name': 'Joseph', 'age': 25},
... {'name': 'Narendra', 'age': 31},
... {'name': 'Angela', 'age': 33},
... {'name': 'Mikhail', 'age': 57},
... ])
>>> array.to_polars_series() # doctest: +NORMALIZE_WHITESPACE
shape: (4,)
Series: '' [struct[2]]
[
{25,"Joseph"}
{31,"Narendra"}
{33,"Angela"}
{57,"Mikhail"}
]
"""
import polars
return polars.from_arrow(self.to_arrow_array()) # pyright: ignore[reportUnknownMemberType]
setattr(Array, "to_polars_series", _Array_to_polars_series)
def _Array_to_numpy(self: _arrays.Array, *, zero_copy_only: bool = True) -> numpy.ndarray:
"""Construct a NumPy array from this Vortex array.
This is an alias for :code:`self.to_arrow_array().to_numpy(zero_copy_only)`
Parameters
----------
zero_copy_only : :class:`bool`
When :obj:`True`, this method will raise an error unless a NumPy array can be created without
copying the data. This is only possible when the array is a primitive array without nulls.
Returns
-------
:class:`numpy.ndarray`
Examples
--------
Construct an immutable ndarray from a Vortex array:
>>> array = vortex.array([1, 0, 0, 1])
>>> array.to_numpy()
array([1, 0, 0, 1])
"""
return self.to_arrow_array().to_numpy(zero_copy_only=zero_copy_only)
Array.to_numpy = _Array_to_numpy
def _Array_to_pylist(self: _arrays.Array) -> list[Any]: # pyright: ignore[reportExplicitAny]
"""Deeply copy an Array into a Python list.
Returns
-------
:class:`list`
Examples
--------
>>> array = vortex.array([
... {'name': 'Joseph', 'age': 25},
... {'name': 'Narendra', 'age': 31},
... {'name': 'Angela', 'age': 33},
... ])
>>> array.to_pylist()
[{'age': 25, 'name': 'Joseph'}, {'age': 31, 'name': 'Narendra'}, {'age': 33, 'name': 'Angela'}]
"""
return self.to_arrow_table().to_pylist()
Array.to_pylist = _Array_to_pylist
def array(
obj: pyarrow.Array[pyarrow.Scalar[Any]] # pyright: ignore[reportExplicitAny]
| pyarrow.ChunkedArray[pyarrow.Scalar[Any]] # pyright: ignore[reportExplicitAny]
| pyarrow.Table
| list[Any] # pyright: ignore[reportExplicitAny]
| pandas.DataFrame
| range,
) -> Array:
"""The main entry point for creating Vortex arrays from other Python objects.
This function is also available as ``vortex.array``.
Parameters
----------
obj : :class:`pyarrow.Array`, :class:`pyarrow.ChunkedArray`, :class:`pyarrow.Table`, :class:`list`,
:class:`pandas.DataFrame`
The elements of this array or list become the elements of the Vortex array.
Returns
-------
:class:`vortex.Array`
Examples
--------
A Vortex array containing the first three integers:
>>> vortex.array([1, 2, 3]).to_arrow_array()
<pyarrow.lib.Int64Array object at ...>
[
1,
2,
3
]
The same Vortex array with a null value in the third position:
>>> vortex.array([1, 2, None, 3]).to_arrow_array()
<pyarrow.lib.Int64Array object at ...>
[
1,
2,
null,
3
]
Initialize a Vortex array from an Arrow array:
>>> arrow = pyarrow.array(['Hello', 'it', 'is', 'me'], type=pyarrow.string_view())
>>> vortex.array(arrow).to_arrow_array()
<pyarrow.lib.StringViewArray object at ...>
[
"Hello",
"it",
"is",
"me"
]
Initialize a Vortex array from a Pandas dataframe:
>>> import pandas as pd
>>> df = pd.DataFrame({
... "Name": ["Braund", "Allen", "Bonnell"],
... "Age": [22, 35, 58],
... })
>>> vortex.array(df).to_arrow_array()
<pyarrow.lib.ChunkedArray object at ...>
[
-- is_valid: all not null
-- child 0 type: string_view
[
"Braund",
"Allen",
"Bonnell"
]
-- child 1 type: int64
[
22,
35,
58
]
]
Initialize a Vortex array from a range:
>>> vortex.array(range(-3, 3)).to_arrow_array()
<pyarrow.lib.Int64Array object at ...>
[
-3,
-2,
-1,
0,
1,
2
]
With a step:
>>> vortex.array(range(-1_000_000, 10_000_000, 2_000_000)).to_arrow_array()
<pyarrow.lib.Int64Array object at ...>
[
-1000000,
1000000,
3000000,
5000000,
7000000,
9000000
]
"""
if isinstance(obj, list):
return Array.from_arrow(pyarrow.array(obj))
if isinstance(obj, range):
return Array.from_range(obj)
try:
import pandas
if isinstance(obj, pandas.DataFrame):
return Array.from_arrow(pyarrow.Table.from_pandas(obj))
except ImportError:
# if we cannot import pandas, it cannot be a pandas DataFrame
assert isinstance(obj, pyarrow.Array | pyarrow.ChunkedArray | pyarrow.Table)
return Array.from_arrow(obj)
class PyArray(Array, metaclass=abc.ABCMeta):
"""Abstract base class for Python-based Vortex arrays."""
@property
@override
@abc.abstractmethod
def id(self) -> str:
"""The id of the array."""
@override
@abc.abstractmethod
def __len__(self) -> int:
"""The logical length of the array."""
@property
@override
@abc.abstractmethod
def dtype(self) -> DType:
"""The data type of the array."""
@classmethod
@abc.abstractmethod
def decode(cls, parts: SerializedArray, ctx: ArrayContext, dtype: DType, len: int) -> Array:
"""Decode an array from its component parts.
:class:`SerializedArray` contains the metadata, buffers and child :class:`SerializedArray`
that represent the current array. Implementations of this function should validate this
information, and then construct a new array.
"""
def _unpickle_array(array_buffers: Sequence[bytes | memoryview], dtype_buffers: Sequence[bytes | memoryview]) -> Array: # pyright: ignore[reportUnusedFunction]
"""Unpickle a Vortex array from IPC-encoded buffer lists.
This is an internal function used by the pickle module for both protocol 4 and 5.
For protocol 4, receives list[bytes] from __reduce__.
For protocol 5, receives list[PickleBuffer/memoryview] from __reduce_ex__.
Both use decode_ipc_array_buffers which concatenates the buffers during deserialization.
"""
return decode_ipc_array_buffers(array_buffers, dtype_buffers)