-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
types.pxi
5318 lines (4221 loc) · 138 KB
/
types.pxi
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
from cpython.pycapsule cimport PyCapsule_CheckExact, PyCapsule_GetPointer, PyCapsule_New, PyCapsule_IsValid
import atexit
from collections.abc import Mapping
import pickle
import re
import sys
import warnings
from cython import sizeof
# These are imprecise because the type (in pandas 0.x) depends on the presence
# of nulls
cdef dict _pandas_type_map = {
_Type_NA: np.object_, # NaNs
_Type_BOOL: np.bool_,
_Type_INT8: np.int8,
_Type_INT16: np.int16,
_Type_INT32: np.int32,
_Type_INT64: np.int64,
_Type_UINT8: np.uint8,
_Type_UINT16: np.uint16,
_Type_UINT32: np.uint32,
_Type_UINT64: np.uint64,
_Type_HALF_FLOAT: np.float16,
_Type_FLOAT: np.float32,
_Type_DOUBLE: np.float64,
# Pandas does not support [D]ay, so default to [ms] for date32
_Type_DATE32: np.dtype('datetime64[ms]'),
_Type_DATE64: np.dtype('datetime64[ms]'),
_Type_TIMESTAMP: {
's': np.dtype('datetime64[s]'),
'ms': np.dtype('datetime64[ms]'),
'us': np.dtype('datetime64[us]'),
'ns': np.dtype('datetime64[ns]'),
},
_Type_DURATION: {
's': np.dtype('timedelta64[s]'),
'ms': np.dtype('timedelta64[ms]'),
'us': np.dtype('timedelta64[us]'),
'ns': np.dtype('timedelta64[ns]'),
},
_Type_BINARY: np.object_,
_Type_FIXED_SIZE_BINARY: np.object_,
_Type_STRING: np.object_,
_Type_LIST: np.object_,
_Type_MAP: np.object_,
_Type_DECIMAL128: np.object_,
}
cdef dict _pep3118_type_map = {
_Type_INT8: b'b',
_Type_INT16: b'h',
_Type_INT32: b'i',
_Type_INT64: b'q',
_Type_UINT8: b'B',
_Type_UINT16: b'H',
_Type_UINT32: b'I',
_Type_UINT64: b'Q',
_Type_HALF_FLOAT: b'e',
_Type_FLOAT: b'f',
_Type_DOUBLE: b'd',
}
cdef bytes _datatype_to_pep3118(CDataType* type):
"""
Construct a PEP 3118 format string describing the given datatype.
None is returned for unsupported types.
"""
try:
char = _pep3118_type_map[type.id()]
except KeyError:
return None
else:
if char in b'bBhHiIqQ':
# Use "standard" int widths, not native
return b'=' + char
else:
return char
cdef void* _as_c_pointer(v, allow_null=False) except *:
"""
Convert a Python object to a raw C pointer.
Used mainly for the C data interface.
Integers are accepted as well as capsule objects with a NULL name.
(the latter for compatibility with raw pointers exported by reticulate)
"""
cdef void* c_ptr
if isinstance(v, int):
c_ptr = <void*> <uintptr_t > v
elif isinstance(v, float):
warnings.warn(
"Passing a pointer value as a float is unsafe and only "
"supported for compatibility with older versions of the R "
"Arrow library", UserWarning, stacklevel=2)
c_ptr = <void*> <uintptr_t > v
elif PyCapsule_CheckExact(v):
c_ptr = PyCapsule_GetPointer(v, NULL)
else:
raise TypeError(f"Expected a pointer value, got {type(v)!r}")
if not allow_null and c_ptr == NULL:
raise ValueError(f"Null pointer (value before cast = {v!r})")
return c_ptr
def _is_primitive(Type type):
# This is simply a redirect, the official API is in pyarrow.types.
return is_primitive(type)
def _get_pandas_type(arrow_type, coerce_to_ns=False):
cdef Type type_id = arrow_type.id
if type_id not in _pandas_type_map:
return None
if coerce_to_ns:
# ARROW-3789: Coerce date/timestamp types to datetime64[ns]
if type_id == _Type_DURATION:
return np.dtype('timedelta64[ns]')
return np.dtype('datetime64[ns]')
pandas_type = _pandas_type_map[type_id]
if isinstance(pandas_type, dict):
unit = getattr(arrow_type, 'unit', None)
pandas_type = pandas_type.get(unit, None)
return pandas_type
def _get_pandas_tz_type(arrow_type, coerce_to_ns=False):
from pyarrow.pandas_compat import make_datetimetz
unit = 'ns' if coerce_to_ns else arrow_type.unit
return make_datetimetz(unit, arrow_type.tz)
def _to_pandas_dtype(arrow_type, options=None):
coerce_to_ns = (options and options.get('coerce_temporal_nanoseconds', False)) or (
_pandas_api.is_v1() and arrow_type.id in
[_Type_DATE32, _Type_DATE64, _Type_TIMESTAMP, _Type_DURATION])
if getattr(arrow_type, 'tz', None):
dtype = _get_pandas_tz_type(arrow_type, coerce_to_ns)
else:
dtype = _get_pandas_type(arrow_type, coerce_to_ns)
if not dtype:
raise NotImplementedError(str(arrow_type))
return dtype
# Workaround for Cython parsing bug
# https://github.com/cython/cython/issues/2143
ctypedef CFixedWidthType* _CFixedWidthTypePtr
cdef class DataType(_Weakrefable):
"""
Base class of all Arrow data types.
Each data type is an *instance* of this class.
Examples
--------
Instance of int64 type:
>>> import pyarrow as pa
>>> pa.int64()
DataType(int64)
"""
def __cinit__(self):
pass
def __init__(self):
raise TypeError("Do not call {}'s constructor directly, use public "
"functions like pyarrow.int64, pyarrow.list_, etc. "
"instead.".format(self.__class__.__name__))
cdef void init(self, const shared_ptr[CDataType]& type) except *:
assert type != nullptr
self.sp_type = type
self.type = type.get()
self.pep3118_format = _datatype_to_pep3118(self.type)
cpdef Field field(self, i):
"""
Parameters
----------
i : int
Returns
-------
pyarrow.Field
"""
if not isinstance(i, int):
raise TypeError(f"Expected int index, got type '{type(i)}'")
cdef int index = <int> _normalize_index(i, self.type.num_fields())
return pyarrow_wrap_field(self.type.field(index))
@property
def id(self):
return self.type.id()
@property
def bit_width(self):
"""
Bit width for fixed width type.
Examples
--------
>>> import pyarrow as pa
>>> pa.int64()
DataType(int64)
>>> pa.int64().bit_width
64
"""
cdef _CFixedWidthTypePtr ty
ty = dynamic_cast[_CFixedWidthTypePtr](self.type)
if ty == nullptr:
raise ValueError("Non-fixed width type")
return ty.bit_width()
@property
def num_fields(self):
"""
The number of child fields.
Examples
--------
>>> import pyarrow as pa
>>> pa.int64()
DataType(int64)
>>> pa.int64().num_fields
0
>>> pa.list_(pa.string())
ListType(list<item: string>)
>>> pa.list_(pa.string()).num_fields
1
>>> struct = pa.struct({'x': pa.int32(), 'y': pa.string()})
>>> struct.num_fields
2
"""
return self.type.num_fields()
@property
def num_buffers(self):
"""
Number of data buffers required to construct Array type
excluding children.
Examples
--------
>>> import pyarrow as pa
>>> pa.int64().num_buffers
2
>>> pa.string().num_buffers
3
"""
return self.type.layout().buffers.size()
def __str__(self):
return frombytes(self.type.ToString(), safe=True)
def __hash__(self):
return hash(str(self))
def __reduce__(self):
return type_for_alias, (str(self),)
def __repr__(self):
return '{0.__class__.__name__}({0})'.format(self)
def __eq__(self, other):
try:
return self.equals(other)
except (TypeError, ValueError):
return NotImplemented
def equals(self, other, *, check_metadata=False):
"""
Return true if type is equivalent to passed value.
Parameters
----------
other : DataType or string convertible to DataType
check_metadata : bool
Whether nested Field metadata equality should be checked as well.
Returns
-------
is_equal : bool
Examples
--------
>>> import pyarrow as pa
>>> pa.int64().equals(pa.string())
False
>>> pa.int64().equals(pa.int64())
True
"""
cdef:
DataType other_type
c_bool c_check_metadata
other_type = ensure_type(other)
c_check_metadata = check_metadata
return self.type.Equals(deref(other_type.type), c_check_metadata)
def to_pandas_dtype(self):
"""
Return the equivalent NumPy / Pandas dtype.
Examples
--------
>>> import pyarrow as pa
>>> pa.int64().to_pandas_dtype()
<class 'numpy.int64'>
"""
return _to_pandas_dtype(self)
def _export_to_c(self, out_ptr):
"""
Export to a C ArrowSchema struct, given its pointer.
Be careful: if you don't pass the ArrowSchema struct to a consumer,
its memory will leak. This is a low-level function intended for
expert users.
"""
check_status(ExportType(deref(self.type),
<ArrowSchema*> _as_c_pointer(out_ptr)))
@staticmethod
def _import_from_c(in_ptr):
"""
Import DataType from a C ArrowSchema struct, given its pointer.
This is a low-level function intended for expert users.
"""
result = GetResultValue(ImportType(<ArrowSchema*>
_as_c_pointer(in_ptr)))
return pyarrow_wrap_data_type(result)
def __arrow_c_schema__(self):
"""
Export to a ArrowSchema PyCapsule
Unlike _export_to_c, this will not leak memory if the capsule is not used.
"""
cdef ArrowSchema* c_schema
capsule = alloc_c_schema(&c_schema)
with nogil:
check_status(ExportType(deref(self.type), c_schema))
return capsule
@staticmethod
def _import_from_c_capsule(schema):
"""
Import a DataType from a ArrowSchema PyCapsule
Parameters
----------
schema : PyCapsule
A valid PyCapsule with name 'arrow_schema' containing an
ArrowSchema pointer.
"""
cdef:
ArrowSchema* c_schema
shared_ptr[CDataType] c_type
if not PyCapsule_IsValid(schema, 'arrow_schema'):
raise TypeError(
"Not an ArrowSchema object"
)
c_schema = <ArrowSchema*> PyCapsule_GetPointer(schema, 'arrow_schema')
with nogil:
c_type = GetResultValue(ImportType(c_schema))
return pyarrow_wrap_data_type(c_type)
cdef class DictionaryMemo(_Weakrefable):
"""
Tracking container for dictionary-encoded fields.
"""
def __cinit__(self):
self.sp_memo.reset(new CDictionaryMemo())
self.memo = self.sp_memo.get()
cdef class DictionaryType(DataType):
"""
Concrete class for dictionary data types.
Examples
--------
Create an instance of dictionary type:
>>> import pyarrow as pa
>>> pa.dictionary(pa.int64(), pa.utf8())
DictionaryType(dictionary<values=string, indices=int64, ordered=0>)
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
self.dict_type = <const CDictionaryType*> type.get()
def __reduce__(self):
return dictionary, (self.index_type, self.value_type, self.ordered)
@property
def ordered(self):
"""
Whether the dictionary is ordered, i.e. whether the ordering of values
in the dictionary is important.
Examples
--------
>>> import pyarrow as pa
>>> pa.dictionary(pa.int64(), pa.utf8()).ordered
False
"""
return self.dict_type.ordered()
@property
def index_type(self):
"""
The data type of dictionary indices (a signed integer type).
Examples
--------
>>> import pyarrow as pa
>>> pa.dictionary(pa.int16(), pa.utf8()).index_type
DataType(int16)
"""
return pyarrow_wrap_data_type(self.dict_type.index_type())
@property
def value_type(self):
"""
The dictionary value type.
The dictionary values are found in an instance of DictionaryArray.
Examples
--------
>>> import pyarrow as pa
>>> pa.dictionary(pa.int16(), pa.utf8()).value_type
DataType(string)
"""
return pyarrow_wrap_data_type(self.dict_type.value_type())
cdef class ListType(DataType):
"""
Concrete class for list data types.
Examples
--------
Create an instance of ListType:
>>> import pyarrow as pa
>>> pa.list_(pa.string())
ListType(list<item: string>)
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
self.list_type = <const CListType*> type.get()
def __reduce__(self):
return list_, (self.value_field,)
@property
def value_field(self):
"""
The field for list values.
Examples
--------
>>> import pyarrow as pa
>>> pa.list_(pa.string()).value_field
pyarrow.Field<item: string>
"""
return pyarrow_wrap_field(self.list_type.value_field())
@property
def value_type(self):
"""
The data type of list values.
Examples
--------
>>> import pyarrow as pa
>>> pa.list_(pa.string()).value_type
DataType(string)
"""
return pyarrow_wrap_data_type(self.list_type.value_type())
cdef class LargeListType(DataType):
"""
Concrete class for large list data types
(like ListType, but with 64-bit offsets).
Examples
--------
Create an instance of LargeListType:
>>> import pyarrow as pa
>>> pa.large_list(pa.string())
LargeListType(large_list<item: string>)
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
self.list_type = <const CLargeListType*> type.get()
def __reduce__(self):
return large_list, (self.value_field,)
@property
def value_field(self):
return pyarrow_wrap_field(self.list_type.value_field())
@property
def value_type(self):
"""
The data type of large list values.
Examples
--------
>>> import pyarrow as pa
>>> pa.large_list(pa.string()).value_type
DataType(string)
"""
return pyarrow_wrap_data_type(self.list_type.value_type())
cdef class MapType(DataType):
"""
Concrete class for map data types.
Examples
--------
Create an instance of MapType:
>>> import pyarrow as pa
>>> pa.map_(pa.string(), pa.int32())
MapType(map<string, int32>)
>>> pa.map_(pa.string(), pa.int32(), keys_sorted=True)
MapType(map<string, int32, keys_sorted>)
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
self.map_type = <const CMapType*> type.get()
def __reduce__(self):
return map_, (self.key_field, self.item_field)
@property
def key_field(self):
"""
The field for keys in the map entries.
Examples
--------
>>> import pyarrow as pa
>>> pa.map_(pa.string(), pa.int32()).key_field
pyarrow.Field<key: string not null>
"""
return pyarrow_wrap_field(self.map_type.key_field())
@property
def key_type(self):
"""
The data type of keys in the map entries.
Examples
--------
>>> import pyarrow as pa
>>> pa.map_(pa.string(), pa.int32()).key_type
DataType(string)
"""
return pyarrow_wrap_data_type(self.map_type.key_type())
@property
def item_field(self):
"""
The field for items in the map entries.
Examples
--------
>>> import pyarrow as pa
>>> pa.map_(pa.string(), pa.int32()).item_field
pyarrow.Field<value: int32>
"""
return pyarrow_wrap_field(self.map_type.item_field())
@property
def item_type(self):
"""
The data type of items in the map entries.
Examples
--------
>>> import pyarrow as pa
>>> pa.map_(pa.string(), pa.int32()).item_type
DataType(int32)
"""
return pyarrow_wrap_data_type(self.map_type.item_type())
@property
def keys_sorted(self):
"""
Should the entries be sorted according to keys.
Examples
--------
>>> import pyarrow as pa
>>> pa.map_(pa.string(), pa.int32(), keys_sorted=True).keys_sorted
True
"""
return self.map_type.keys_sorted()
cdef class FixedSizeListType(DataType):
"""
Concrete class for fixed size list data types.
Examples
--------
Create an instance of FixedSizeListType:
>>> import pyarrow as pa
>>> pa.list_(pa.int32(), 2)
FixedSizeListType(fixed_size_list<item: int32>[2])
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
self.list_type = <const CFixedSizeListType*> type.get()
def __reduce__(self):
return list_, (self.value_type, self.list_size)
@property
def value_field(self):
"""
The field for list values.
Examples
--------
>>> import pyarrow as pa
>>> pa.list_(pa.int32(), 2).value_field
pyarrow.Field<item: int32>
"""
return pyarrow_wrap_field(self.list_type.value_field())
@property
def value_type(self):
"""
The data type of large list values.
Examples
--------
>>> import pyarrow as pa
>>> pa.list_(pa.int32(), 2).value_type
DataType(int32)
"""
return pyarrow_wrap_data_type(self.list_type.value_type())
@property
def list_size(self):
"""
The size of the fixed size lists.
Examples
--------
>>> import pyarrow as pa
>>> pa.list_(pa.int32(), 2).list_size
2
"""
return self.list_type.list_size()
cdef class StructType(DataType):
"""
Concrete class for struct data types.
``StructType`` supports direct indexing using ``[...]`` (implemented via
``__getitem__``) to access its fields.
It will return the struct field with the given index or name.
Examples
--------
>>> import pyarrow as pa
Accessing fields using direct indexing:
>>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()})
>>> struct_type[0]
pyarrow.Field<x: int32>
>>> struct_type['y']
pyarrow.Field<y: string>
Accessing fields using ``field()``:
>>> struct_type.field(1)
pyarrow.Field<y: string>
>>> struct_type.field('x')
pyarrow.Field<x: int32>
# Creating a schema from the struct type's fields:
>>> pa.schema(list(struct_type))
x: int32
y: string
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
self.struct_type = <const CStructType*> type.get()
cdef Field field_by_name(self, name):
"""
Return a child field by its name.
Parameters
----------
name : str
The name of the field to look up.
Returns
-------
field : Field
The child field with the given name.
Raises
------
KeyError
If the name isn't found, or if several fields have the given
name.
"""
cdef vector[shared_ptr[CField]] fields
fields = self.struct_type.GetAllFieldsByName(tobytes(name))
if fields.size() == 0:
raise KeyError(name)
elif fields.size() > 1:
warnings.warn("Struct field name corresponds to more "
"than one field", UserWarning)
raise KeyError(name)
else:
return pyarrow_wrap_field(fields[0])
def get_field_index(self, name):
"""
Return index of the unique field with the given name.
Parameters
----------
name : str
The name of the field to look up.
Returns
-------
index : int
The index of the field with the given name; -1 if the
name isn't found or there are several fields with the given
name.
Examples
--------
>>> import pyarrow as pa
>>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()})
Index of the field with a name 'y':
>>> struct_type.get_field_index('y')
1
Index of the field that does not exist:
>>> struct_type.get_field_index('z')
-1
"""
return self.struct_type.GetFieldIndex(tobytes(name))
cpdef Field field(self, i):
"""
Select a field by its column name or numeric index.
Parameters
----------
i : int or str
Returns
-------
pyarrow.Field
Examples
--------
>>> import pyarrow as pa
>>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()})
Select the second field:
>>> struct_type.field(1)
pyarrow.Field<y: string>
Select the field named 'x':
>>> struct_type.field('x')
pyarrow.Field<x: int32>
"""
if isinstance(i, (bytes, str)):
return self.field_by_name(i)
elif isinstance(i, int):
return DataType.field(self, i)
else:
raise TypeError('Expected integer or string index')
def get_all_field_indices(self, name):
"""
Return sorted list of indices for the fields with the given name.
Parameters
----------
name : str
The name of the field to look up.
Returns
-------
indices : List[int]
Examples
--------
>>> import pyarrow as pa
>>> struct_type = pa.struct({'x': pa.int32(), 'y': pa.string()})
>>> struct_type.get_all_field_indices('x')
[0]
"""
return self.struct_type.GetAllFieldIndices(tobytes(name))
def __len__(self):
"""
Like num_fields().
"""
return self.type.num_fields()
def __iter__(self):
"""
Iterate over struct fields, in order.
"""
for i in range(len(self)):
yield self[i]
def __getitem__(self, i):
"""
Return the struct field with the given index or name.
Alias of ``field``.
"""
return self.field(i)
def __reduce__(self):
return struct, (list(self),)
cdef class UnionType(DataType):
"""
Base class for union data types.
Examples
--------
Create an instance of a dense UnionType using ``pa.union``:
>>> import pyarrow as pa
>>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())],
... mode=pa.lib.UnionMode_DENSE),
(DenseUnionType(dense_union<a: fixed_size_binary[10]=0, b: string=1>),)
Create an instance of a dense UnionType using ``pa.dense_union``:
>>> pa.dense_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())])
DenseUnionType(dense_union<a: fixed_size_binary[10]=0, b: string=1>)
Create an instance of a sparse UnionType using ``pa.union``:
>>> pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())],
... mode=pa.lib.UnionMode_SPARSE),
(SparseUnionType(sparse_union<a: fixed_size_binary[10]=0, b: string=1>),)
Create an instance of a sparse UnionType using ``pa.sparse_union``:
>>> pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())])
SparseUnionType(sparse_union<a: fixed_size_binary[10]=0, b: string=1>)
"""
cdef void init(self, const shared_ptr[CDataType]& type) except *:
DataType.init(self, type)
@property
def mode(self):
"""
The mode of the union ("dense" or "sparse").
Examples
--------
>>> import pyarrow as pa
>>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())])
>>> union.mode
'sparse'
"""
cdef CUnionType* type = <CUnionType*> self.sp_type.get()
cdef int mode = type.mode()
if mode == _UnionMode_DENSE:
return 'dense'
if mode == _UnionMode_SPARSE:
return 'sparse'
assert 0
@property
def type_codes(self):
"""
The type code to indicate each data type in this union.
Examples
--------
>>> import pyarrow as pa
>>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())])
>>> union.type_codes
[0, 1]
"""
cdef CUnionType* type = <CUnionType*> self.sp_type.get()
return type.type_codes()
def __len__(self):
"""
Like num_fields().
"""
return self.type.num_fields()
def __iter__(self):
"""
Iterate over union members, in order.
"""
for i in range(len(self)):
yield self[i]
cpdef Field field(self, i):
"""
Return a child field by its numeric index.
Parameters
----------
i : int
Returns
-------
pyarrow.Field
Examples
--------
>>> import pyarrow as pa
>>> union = pa.sparse_union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())])
>>> union[0]
pyarrow.Field<a: fixed_size_binary[10]>
"""
if isinstance(i, int):
return DataType.field(self, i)
else:
raise TypeError('Expected integer')
def __getitem__(self, i):
"""
Return a child field by its index.