forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.pxi
More file actions
798 lines (608 loc) · 21.3 KB
/
array.pxi
File metadata and controls
798 lines (608 loc) · 21.3 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
cdef _sequence_to_array(object sequence, object size, DataType type,
CMemoryPool* pool):
cdef shared_ptr[CArray] out
cdef int64_t c_size
if type is None:
with nogil:
check_status(ConvertPySequence(sequence, pool, &out))
else:
if size is None:
with nogil:
check_status(
ConvertPySequence(
sequence, pool, &out, type.sp_type
)
)
else:
c_size = size
with nogil:
check_status(
ConvertPySequence(
sequence, pool, &out, type.sp_type, c_size
)
)
return pyarrow_wrap_array(out)
cdef _is_array_like(obj):
try:
import pandas
return isinstance(obj, (np.ndarray, pd.Series, pd.Index, Categorical))
except ImportError:
return isinstance(obj, np.ndarray)
cdef _ndarray_to_array(object values, object mask, DataType type,
c_bool use_pandas_null_sentinels,
CMemoryPool* pool):
cdef shared_ptr[CChunkedArray] chunked_out
cdef shared_ptr[CDataType] c_type
dtype = values.dtype
if type is None and dtype != object:
with nogil:
check_status(NumPyDtypeToArrow(dtype, &c_type))
if type is not None:
c_type = type.sp_type
with nogil:
check_status(NdarrayToArrow(pool, values, mask,
use_pandas_null_sentinels,
c_type, &chunked_out))
if chunked_out.get().num_chunks() > 1:
return pyarrow_wrap_chunked_array(chunked_out)
else:
return pyarrow_wrap_array(chunked_out.get().chunk(0))
cdef DataType _ensure_type(object type):
if type is None:
return None
elif not isinstance(type, DataType):
return type_for_alias(type)
else:
return type
def array(object obj, type=None, mask=None,
MemoryPool memory_pool=None, size=None,
from_pandas=False):
"""
Create pyarrow.Array instance from a Python object
Parameters
----------
obj : sequence, iterable, ndarray or Series
If both type and size are specified may be a single use iterable. If
not strongly-typed, Arrow type will be inferred for resulting array
mask : array (boolean), optional
Indicate which values are null (True) or not null (False).
type : pyarrow.DataType
Explicit type to attempt to coerce to, otherwise will be inferred from
the data
memory_pool : pyarrow.MemoryPool, optional
If not passed, will allocate memory from the currently-set default
memory pool
size : int64, optional
Size of the elements. If the imput is larger than size bail at this
length. For iterators, if size is larger than the input iterator this
will be treated as a "max size", but will involve an initial allocation
of size followed by a resize to the actual size (so if you know the
exact size specifying it correctly will give you better performance).
from_pandas : boolean, default False
Use pandas's semantics for inferring nulls from values in ndarray-like
data. If passed, the mask tasks precendence, but if a value is unmasked
(not-null), but still null according to pandas semantics, then it is
null
Notes
-----
Localized timestamps will currently be returned as UTC (pandas's native
representation). Timezone-naive data will be implicitly interpreted as
UTC.
Examples
--------
>>> import pandas as pd
>>> import pyarrow as pa
>>> pa.array(pd.Series([1, 2]))
<pyarrow.array.Int64Array object at 0x7f674e4c0e10>
[
1,
2
]
>>> import numpy as np
>>> pa.array(pd.Series([1, 2]), np.array([0, 1],
... dtype=bool))
<pyarrow.array.Int64Array object at 0x7f9019e11208>
[
1,
NA
]
Returns
-------
array : pyarrow.Array or pyarrow.ChunkedArray (if object data
overflowed binary storage)
"""
type = _ensure_type(type)
cdef CMemoryPool* pool = maybe_unbox_memory_pool(memory_pool)
if _is_array_like(obj):
if mask is not None:
mask = get_series_values(mask)
values = get_series_values(obj)
if isinstance(values, Categorical):
return DictionaryArray.from_arrays(
values.codes, values.categories.values,
mask=mask, ordered=values.ordered,
memory_pool=memory_pool)
else:
values, type = pdcompat.get_datetimetz_type(values, obj.dtype,
type)
return _ndarray_to_array(values, mask, type, from_pandas, pool)
else:
if mask is not None:
raise ValueError("Masks only supported with ndarray-like inputs")
return _sequence_to_array(obj, size, type, pool)
def asarray(values, type=None):
"""
Convert to pyarrow.Array, inferring type if not provided. Attempt to cast
if indicated type is different
Parameters
----------
values : array-like (sequence, numpy.ndarray, pyarrow.Array)
type : string or DataType
Returns
-------
arr : Array
"""
if isinstance(values, Array):
if type is not None and not values.type.equals(type):
values = values.cast(type)
return values
else:
return array(values, type=type)
def _normalize_slice(object arrow_obj, slice key):
cdef Py_ssize_t n = len(arrow_obj)
start = key.start or 0
while start < 0:
start += n
stop = key.stop if key.stop is not None else n
while stop < 0:
stop += n
step = key.step or 1
if step != 1:
raise IndexError('only slices with step 1 supported')
else:
return arrow_obj.slice(start, stop - start)
cdef class _FunctionContext:
cdef:
unique_ptr[CFunctionContext] ctx
def __cinit__(self):
self.ctx.reset(new CFunctionContext(c_default_memory_pool()))
cdef _FunctionContext _global_ctx = _FunctionContext()
cdef CFunctionContext* _context() nogil:
return _global_ctx.ctx.get()
cdef class Array:
cdef void init(self, const shared_ptr[CArray]& sp_array):
self.sp_array = sp_array
self.ap = sp_array.get()
self.type = pyarrow_wrap_data_type(self.sp_array.get().type())
def _debug_print(self):
with nogil:
check_status(DebugPrint(deref(self.ap), 0))
def cast(self, object target_type, safe=True):
"""
Cast array values to another data type
Parameters
----------
target_type : DataType
Type to cast to
safe : boolean, default True
Check for overflows or other unsafe conversions
Returns
-------
casted : Array
"""
cdef:
CCastOptions options
shared_ptr[CArray] result
DataType type
type = _ensure_type(target_type)
if not safe:
options.allow_int_overflow = 1
with nogil:
check_status(Cast(_context(), self.ap[0], type.sp_type,
options, &result))
return pyarrow_wrap_array(result)
@staticmethod
def from_pandas(obj, mask=None, type=None, MemoryPool memory_pool=None):
"""
Convert pandas.Series to an Arrow Array, using pandas's semantics about
what values indicate nulls. See pyarrow.array for more general
conversion from arrays or sequences to Arrow arrays
Parameters
----------
sequence : ndarray, Inded Series
mask : array (boolean), optional
Indicate which values are null (True) or not null (False)
type : pyarrow.DataType
Explicit type to attempt to coerce to, otherwise will be inferred
from the data
memory_pool : pyarrow.MemoryPool, optional
If not passed, will allocate memory from the currently-set default
memory pool
Notes
-----
Localized timestamps will currently be returned as UTC (pandas's native
representation). Timezone-naive data will be implicitly interpreted as
UTC.
Returns
-------
array : pyarrow.Array or pyarrow.ChunkedArray (if object data
overflows binary buffer)
"""
return array(obj, mask=mask, type=type, memory_pool=memory_pool,
from_pandas=True)
property null_count:
def __get__(self):
return self.sp_array.get().null_count()
def __iter__(self):
for i in range(len(self)):
yield self.getitem(i)
raise StopIteration
def __repr__(self):
from pyarrow.formatting import array_format
type_format = object.__repr__(self)
values = array_format(self, window=10)
return '{0}\n{1}'.format(type_format, values)
def equals(Array self, Array other):
return self.ap.Equals(deref(other.ap))
def __len__(self):
if self.sp_array.get():
return self.sp_array.get().length()
else:
return 0
def isnull(self):
raise NotImplemented
def __getitem__(self, key):
cdef Py_ssize_t n = len(self)
if PySlice_Check(key):
return _normalize_slice(self, key)
while key < 0:
key += len(self)
return self.getitem(key)
cdef getitem(self, int64_t i):
return box_scalar(self.type, self.sp_array, i)
def slice(self, offset=0, length=None):
"""
Compute zero-copy slice of this array
Parameters
----------
offset : int, default 0
Offset from start of array to slice
length : int, default None
Length of slice (default is until end of Array starting from
offset)
Returns
-------
sliced : RecordBatch
"""
cdef:
shared_ptr[CArray] result
if offset < 0:
raise IndexError('Offset must be non-negative')
if length is None:
result = self.ap.Slice(offset)
else:
result = self.ap.Slice(offset, length)
return pyarrow_wrap_array(result)
def to_pandas(self, c_bool strings_to_categorical=False):
"""
Convert to an array object suitable for use in pandas
Parameters
----------
strings_to_categorical : boolean, default False
Encode string (UTF8) and binary types to pandas.Categorical
See also
--------
Column.to_pandas
Table.to_pandas
RecordBatch.to_pandas
"""
cdef:
PyObject* out
PandasOptions options
options = PandasOptions(strings_to_categorical=strings_to_categorical)
with nogil:
check_status(ConvertArrayToPandas(options, self.sp_array,
self, &out))
return wrap_array_output(out)
def to_pylist(self):
"""
Convert to an list of native Python objects.
"""
return [x.as_py() for x in self]
def validate(self):
"""
Perform any validation checks implemented by
arrow::ValidateArray. Raises exception with error message if array does
not validate
Raises
------
ArrowInvalid
"""
with nogil:
check_status(ValidateArray(deref(self.ap)))
cdef class Tensor:
cdef void init(self, const shared_ptr[CTensor]& sp_tensor):
self.sp_tensor = sp_tensor
self.tp = sp_tensor.get()
self.type = pyarrow_wrap_data_type(self.tp.type())
def __repr__(self):
return """<pyarrow.Tensor>
type: {0}
shape: {1}
strides: {2}""".format(self.type, self.shape, self.strides)
@staticmethod
def from_numpy(obj):
cdef shared_ptr[CTensor] ctensor
with nogil:
check_status(NdarrayToTensor(c_default_memory_pool(), obj,
&ctensor))
return pyarrow_wrap_tensor(ctensor)
def to_numpy(self):
"""
Convert arrow::Tensor to numpy.ndarray with zero copy
"""
cdef:
PyObject* out
with nogil:
check_status(TensorToNdarray(deref(self.tp), self, &out))
return PyObject_to_object(out)
def equals(self, Tensor other):
"""
Return true if the tensors contains exactly equal data
"""
return self.tp.Equals(deref(other.tp))
property is_mutable:
def __get__(self):
return self.tp.is_mutable()
property is_contiguous:
def __get__(self):
return self.tp.is_contiguous()
property ndim:
def __get__(self):
return self.tp.ndim()
property size:
def __get__(self):
return self.tp.size()
property shape:
def __get__(self):
cdef size_t i
py_shape = []
for i in range(self.tp.shape().size()):
py_shape.append(self.tp.shape()[i])
return py_shape
property strides:
def __get__(self):
cdef size_t i
py_strides = []
for i in range(self.tp.strides().size()):
py_strides.append(self.tp.strides()[i])
return py_strides
cdef wrap_array_output(PyObject* output):
cdef object obj = PyObject_to_object(output)
if isinstance(obj, dict):
return Categorical(obj['indices'],
categories=obj['dictionary'],
fastpath=True)
else:
return obj
cdef class NullArray(Array):
pass
cdef class BooleanArray(Array):
pass
cdef class NumericArray(Array):
pass
cdef class IntegerArray(NumericArray):
pass
cdef class FloatingPointArray(NumericArray):
pass
cdef class Int8Array(IntegerArray):
pass
cdef class UInt8Array(IntegerArray):
pass
cdef class Int16Array(IntegerArray):
pass
cdef class UInt16Array(IntegerArray):
pass
cdef class Int32Array(IntegerArray):
pass
cdef class UInt32Array(IntegerArray):
pass
cdef class Int64Array(IntegerArray):
pass
cdef class UInt64Array(IntegerArray):
pass
cdef class Date32Array(NumericArray):
pass
cdef class Date64Array(NumericArray):
pass
cdef class TimestampArray(NumericArray):
pass
cdef class Time32Array(NumericArray):
pass
cdef class Time64Array(NumericArray):
pass
cdef class FloatArray(FloatingPointArray):
pass
cdef class DoubleArray(FloatingPointArray):
pass
cdef class FixedSizeBinaryArray(Array):
pass
cdef class DecimalArray(FixedSizeBinaryArray):
pass
cdef class ListArray(Array):
@staticmethod
def from_arrays(offsets, values, MemoryPool pool=None):
"""
Construct ListArray from arrays of int32 offsets and values
Parameters
----------
offset : Array (int32 type)
values : Array (any type)
Returns
-------
list_array : ListArray
"""
cdef:
Array _offsets, _values
shared_ptr[CArray] out
cdef CMemoryPool* cpool = maybe_unbox_memory_pool(pool)
_offsets = asarray(offsets, type='int32')
_values = asarray(values)
with nogil:
check_status(CListArray.FromArrays(_offsets.ap[0], _values.ap[0],
cpool, &out))
return pyarrow_wrap_array(out)
cdef class StringArray(Array):
pass
cdef class BinaryArray(Array):
pass
cdef class DictionaryArray(Array):
cdef getitem(self, int64_t i):
cdef Array dictionary = self.dictionary
index = self.indices[i]
if index is NA:
return index
else:
return box_scalar(dictionary.type, dictionary.sp_array,
index.as_py())
property dictionary:
def __get__(self):
cdef CDictionaryArray* darr = <CDictionaryArray*>(self.ap)
if self._dictionary is None:
self._dictionary = pyarrow_wrap_array(darr.dictionary())
return self._dictionary
property indices:
def __get__(self):
cdef CDictionaryArray* darr = <CDictionaryArray*>(self.ap)
if self._indices is None:
self._indices = pyarrow_wrap_array(darr.indices())
return self._indices
@staticmethod
def from_arrays(indices, dictionary, mask=None, ordered=False,
MemoryPool memory_pool=None):
"""
Construct Arrow DictionaryArray from array of indices (must be
non-negative integers) and corresponding array of dictionary values
Parameters
----------
indices : ndarray or pandas.Series, integer type
dictionary : ndarray or pandas.Series
mask : ndarray or pandas.Series, boolean type
True values indicate that indices are actually null
ordered : boolean, default False
Set to True if the category values are ordered
Returns
-------
dict_array : DictionaryArray
"""
cdef:
Array arrow_indices, arrow_dictionary
DictionaryArray result
shared_ptr[CDataType] c_type
shared_ptr[CArray] c_result
if isinstance(indices, Array):
if mask is not None:
raise NotImplementedError(
"mask not implemented with Arrow array inputs yet")
arrow_indices = indices
else:
if mask is None:
mask = indices == -1
else:
mask = mask | (indices == -1)
arrow_indices = Array.from_pandas(indices, mask=mask,
memory_pool=memory_pool)
if isinstance(dictionary, Array):
arrow_dictionary = dictionary
else:
arrow_dictionary = Array.from_pandas(dictionary,
memory_pool=memory_pool)
if not isinstance(arrow_indices, IntegerArray):
raise ValueError('Indices must be integer type')
cdef c_bool c_ordered = ordered
c_type.reset(new CDictionaryType(arrow_indices.type.sp_type,
arrow_dictionary.sp_array, c_ordered))
c_result.reset(new CDictionaryArray(c_type, arrow_indices.sp_array))
result = DictionaryArray()
result.init(c_result)
return result
cdef class StructArray(Array):
@staticmethod
def from_arrays(field_names, arrays):
cdef:
Array array
shared_ptr[CArray] c_array
vector[shared_ptr[CArray]] c_arrays
shared_ptr[CArray] c_result
ssize_t num_arrays
ssize_t length
ssize_t i
num_arrays = len(arrays)
if num_arrays == 0:
raise ValueError("arrays list is empty")
length = len(arrays[0])
c_arrays.resize(num_arrays)
for i in range(num_arrays):
array = arrays[i]
if len(array) != length:
raise ValueError("All arrays must have the same length")
c_arrays[i] = array.sp_array
cdef DataType struct_type = struct([
field(name, array.type)
for name, array in
zip(field_names, arrays)
])
c_result.reset(new CStructArray(struct_type.sp_type, length, c_arrays))
result = StructArray()
result.init(c_result)
return result
cdef dict _array_classes = {
_Type_NA: NullArray,
_Type_BOOL: BooleanArray,
_Type_UINT8: UInt8Array,
_Type_UINT16: UInt16Array,
_Type_UINT32: UInt32Array,
_Type_UINT64: UInt64Array,
_Type_INT8: Int8Array,
_Type_INT16: Int16Array,
_Type_INT32: Int32Array,
_Type_INT64: Int64Array,
_Type_DATE32: Date32Array,
_Type_DATE64: Date64Array,
_Type_TIMESTAMP: TimestampArray,
_Type_TIME32: Time32Array,
_Type_TIME64: Time64Array,
_Type_FLOAT: FloatArray,
_Type_DOUBLE: DoubleArray,
_Type_LIST: ListArray,
_Type_BINARY: BinaryArray,
_Type_STRING: StringArray,
_Type_DICTIONARY: DictionaryArray,
_Type_FIXED_SIZE_BINARY: FixedSizeBinaryArray,
_Type_DECIMAL: DecimalArray,
_Type_STRUCT: StructArray,
}
cdef object get_series_values(object obj):
if isinstance(obj, PandasSeries):
result = obj.values
elif isinstance(obj, np.ndarray):
result = obj
else:
result = PandasSeries(obj).values
return result