-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
/
Copy patharray.py
2917 lines (2542 loc) · 101 KB
/
array.py
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
from __future__ import annotations
import functools
import operator
import re
import textwrap
from typing import (
TYPE_CHECKING,
Any,
Literal,
cast,
overload,
)
import unicodedata
import numpy as np
from pandas._libs import lib
from pandas._libs.tslibs import (
Timedelta,
Timestamp,
timezones,
)
from pandas.compat import (
pa_version_under10p1,
pa_version_under11p0,
pa_version_under13p0,
)
from pandas.util._decorators import doc
from pandas.core.dtypes.cast import (
can_hold_element,
infer_dtype_from_scalar,
)
from pandas.core.dtypes.common import (
CategoricalDtype,
is_array_like,
is_bool_dtype,
is_float_dtype,
is_integer,
is_list_like,
is_numeric_dtype,
is_scalar,
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.dtypes.missing import isna
from pandas.core import (
algorithms as algos,
missing,
ops,
roperator,
)
from pandas.core.algorithms import map_array
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays._arrow_string_mixins import ArrowStringArrayMixin
from pandas.core.arrays._utils import to_numpy_dtype_inference
from pandas.core.arrays.base import (
ExtensionArray,
ExtensionArraySupportsAnyAll,
)
from pandas.core.arrays.masked import BaseMaskedArray
from pandas.core.arrays.string_ import StringDtype
import pandas.core.common as com
from pandas.core.indexers import (
check_array_indexer,
unpack_tuple_and_ellipses,
validate_indices,
)
from pandas.core.nanops import check_below_min_count
from pandas.core.strings.base import BaseStringArrayMethods
from pandas.io._util import _arrow_dtype_mapping
from pandas.tseries.frequencies import to_offset
if not pa_version_under10p1:
import pyarrow as pa
import pyarrow.compute as pc
from pandas.core.dtypes.dtypes import ArrowDtype
ARROW_CMP_FUNCS = {
"eq": pc.equal,
"ne": pc.not_equal,
"lt": pc.less,
"gt": pc.greater,
"le": pc.less_equal,
"ge": pc.greater_equal,
}
ARROW_LOGICAL_FUNCS = {
"and_": pc.and_kleene,
"rand_": lambda x, y: pc.and_kleene(y, x),
"or_": pc.or_kleene,
"ror_": lambda x, y: pc.or_kleene(y, x),
"xor": pc.xor,
"rxor": lambda x, y: pc.xor(y, x),
}
ARROW_BIT_WISE_FUNCS = {
"and_": pc.bit_wise_and,
"rand_": lambda x, y: pc.bit_wise_and(y, x),
"or_": pc.bit_wise_or,
"ror_": lambda x, y: pc.bit_wise_or(y, x),
"xor": pc.bit_wise_xor,
"rxor": lambda x, y: pc.bit_wise_xor(y, x),
}
def cast_for_truediv(
arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar
) -> tuple[pa.ChunkedArray, pa.Array | pa.Scalar]:
# Ensure int / int -> float mirroring Python/Numpy behavior
# as pc.divide_checked(int, int) -> int
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
pa_object.type
):
# GH: 56645.
# https://github.com/apache/arrow/issues/35563
return pc.cast(arrow_array, pa.float64(), safe=False), pc.cast(
pa_object, pa.float64(), safe=False
)
return arrow_array, pa_object
def floordiv_compat(
left: pa.ChunkedArray | pa.Array | pa.Scalar,
right: pa.ChunkedArray | pa.Array | pa.Scalar,
) -> pa.ChunkedArray:
# TODO: Replace with pyarrow floordiv kernel.
# https://github.com/apache/arrow/issues/39386
if pa.types.is_integer(left.type) and pa.types.is_integer(right.type):
divided = pc.divide_checked(left, right)
if pa.types.is_signed_integer(divided.type):
# GH 56676
has_remainder = pc.not_equal(pc.multiply(divided, right), left)
has_one_negative_operand = pc.less(
pc.bit_wise_xor(left, right),
pa.scalar(0, type=divided.type),
)
result = pc.if_else(
pc.and_(
has_remainder,
has_one_negative_operand,
),
# GH: 55561
pc.subtract(divided, pa.scalar(1, type=divided.type)),
divided,
)
else:
result = divided
result = result.cast(left.type)
else:
divided = pc.divide(left, right)
result = pc.floor(divided)
return result
ARROW_ARITHMETIC_FUNCS = {
"add": pc.add_checked,
"radd": lambda x, y: pc.add_checked(y, x),
"sub": pc.subtract_checked,
"rsub": lambda x, y: pc.subtract_checked(y, x),
"mul": pc.multiply_checked,
"rmul": lambda x, y: pc.multiply_checked(y, x),
"truediv": lambda x, y: pc.divide(*cast_for_truediv(x, y)),
"rtruediv": lambda x, y: pc.divide(*cast_for_truediv(y, x)),
"floordiv": lambda x, y: floordiv_compat(x, y),
"rfloordiv": lambda x, y: floordiv_compat(y, x),
"mod": NotImplemented,
"rmod": NotImplemented,
"divmod": NotImplemented,
"rdivmod": NotImplemented,
"pow": pc.power_checked,
"rpow": lambda x, y: pc.power_checked(y, x),
}
if TYPE_CHECKING:
from collections.abc import (
Callable,
Sequence,
)
from pandas._libs.missing import NAType
from pandas._typing import (
ArrayLike,
AxisInt,
Dtype,
FillnaOptions,
InterpolateOptions,
Iterator,
NpDtype,
NumpySorter,
NumpyValueArrayLike,
PositionalIndexer,
Scalar,
Self,
SortKind,
TakeIndexer,
TimeAmbiguous,
TimeNonexistent,
npt,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas import Series
from pandas.core.arrays.datetimes import DatetimeArray
from pandas.core.arrays.timedeltas import TimedeltaArray
def get_unit_from_pa_dtype(pa_dtype) -> str:
# https://github.com/pandas-dev/pandas/pull/50998#discussion_r1100344804
if pa_version_under11p0:
unit = str(pa_dtype).split("[", 1)[-1][:-1]
if unit not in ["s", "ms", "us", "ns"]:
raise ValueError(pa_dtype)
return unit
return pa_dtype.unit
def to_pyarrow_type(
dtype: ArrowDtype | pa.DataType | Dtype | None,
) -> pa.DataType | None:
"""
Convert dtype to a pyarrow type instance.
"""
if isinstance(dtype, ArrowDtype):
return dtype.pyarrow_dtype
elif isinstance(dtype, pa.DataType):
return dtype
elif isinstance(dtype, DatetimeTZDtype):
return pa.timestamp(dtype.unit, dtype.tz)
elif dtype:
try:
# Accepts python types too
# Doesn't handle all numpy types
return pa.from_numpy_dtype(dtype)
except pa.ArrowNotImplementedError:
pass
return None
class ArrowExtensionArray(
OpsMixin,
ExtensionArraySupportsAnyAll,
ArrowStringArrayMixin,
BaseStringArrayMethods,
):
"""
Pandas ExtensionArray backed by a PyArrow ChunkedArray.
.. warning::
ArrowExtensionArray is considered experimental. The implementation and
parts of the API may change without warning.
Parameters
----------
values : pyarrow.Array or pyarrow.ChunkedArray
Attributes
----------
None
Methods
-------
None
Returns
-------
ArrowExtensionArray
Notes
-----
Most methods are implemented using `pyarrow compute functions. <https://arrow.apache.org/docs/python/api/compute.html>`__
Some methods may either raise an exception or raise a ``PerformanceWarning`` if an
associated compute function is not available based on the installed version of PyArrow.
Please install the latest version of PyArrow to enable the best functionality and avoid
potential bugs in prior versions of PyArrow.
Examples
--------
Create an ArrowExtensionArray with :func:`pandas.array`:
>>> pd.array([1, 1, None], dtype="int64[pyarrow]")
<ArrowExtensionArray>
[1, 1, <NA>]
Length: 3, dtype: int64[pyarrow]
""" # noqa: E501 (http link too long)
_pa_array: pa.ChunkedArray
_dtype: ArrowDtype
def __init__(self, values: pa.Array | pa.ChunkedArray) -> None:
if pa_version_under10p1:
msg = "pyarrow>=10.0.1 is required for PyArrow backed ArrowExtensionArray."
raise ImportError(msg)
if isinstance(values, pa.Array):
self._pa_array = pa.chunked_array([values])
elif isinstance(values, pa.ChunkedArray):
self._pa_array = values
else:
raise ValueError(
f"Unsupported type '{type(values)}' for ArrowExtensionArray"
)
self._dtype = ArrowDtype(self._pa_array.type)
@classmethod
def _from_sequence(
cls, scalars, *, dtype: Dtype | None = None, copy: bool = False
) -> Self:
"""
Construct a new ExtensionArray from a sequence of scalars.
"""
pa_type = to_pyarrow_type(dtype)
pa_array = cls._box_pa_array(scalars, pa_type=pa_type, copy=copy)
arr = cls(pa_array)
return arr
@classmethod
def _from_sequence_of_strings(
cls, strings, *, dtype: ExtensionDtype, copy: bool = False
) -> Self:
"""
Construct a new ExtensionArray from a sequence of strings.
"""
pa_type = to_pyarrow_type(dtype)
if (
pa_type is None
or pa.types.is_binary(pa_type)
or pa.types.is_string(pa_type)
or pa.types.is_large_string(pa_type)
):
# pa_type is None: Let pa.array infer
# pa_type is string/binary: scalars already correct type
scalars = strings
elif pa.types.is_timestamp(pa_type):
from pandas.core.tools.datetimes import to_datetime
scalars = to_datetime(strings, errors="raise")
elif pa.types.is_date(pa_type):
from pandas.core.tools.datetimes import to_datetime
scalars = to_datetime(strings, errors="raise").date
elif pa.types.is_duration(pa_type):
from pandas.core.tools.timedeltas import to_timedelta
scalars = to_timedelta(strings, errors="raise")
if pa_type.unit != "ns":
# GH51175: test_from_sequence_of_strings_pa_array
# attempt to parse as int64 reflecting pyarrow's
# duration to string casting behavior
mask = isna(scalars)
if not isinstance(strings, (pa.Array, pa.ChunkedArray)):
strings = pa.array(strings, type=pa.string(), from_pandas=True)
strings = pc.if_else(mask, None, strings)
try:
scalars = strings.cast(pa.int64())
except pa.ArrowInvalid:
pass
elif pa.types.is_time(pa_type):
from pandas.core.tools.times import to_time
# "coerce" to allow "null times" (None) to not raise
scalars = to_time(strings, errors="coerce")
elif pa.types.is_boolean(pa_type):
# pyarrow string->bool casting is case-insensitive:
# "true" or "1" -> True
# "false" or "0" -> False
# Note: BooleanArray was previously used to parse these strings
# and allows "1.0" and "0.0". Pyarrow casting does not support
# this, but we allow it here.
if isinstance(strings, (pa.Array, pa.ChunkedArray)):
scalars = strings
else:
scalars = pa.array(strings, type=pa.string(), from_pandas=True)
scalars = pc.if_else(pc.equal(scalars, "1.0"), "1", scalars)
scalars = pc.if_else(pc.equal(scalars, "0.0"), "0", scalars)
scalars = scalars.cast(pa.bool_())
elif (
pa.types.is_integer(pa_type)
or pa.types.is_floating(pa_type)
or pa.types.is_decimal(pa_type)
):
from pandas.core.tools.numeric import to_numeric
scalars = to_numeric(strings, errors="raise")
else:
raise NotImplementedError(
f"Converting strings to {pa_type} is not implemented."
)
return cls._from_sequence(scalars, dtype=pa_type, copy=copy)
@classmethod
def _box_pa(
cls, value, pa_type: pa.DataType | None = None
) -> pa.Array | pa.ChunkedArray | pa.Scalar:
"""
Box value into a pyarrow Array, ChunkedArray or Scalar.
Parameters
----------
value : any
pa_type : pa.DataType | None
Returns
-------
pa.Array or pa.ChunkedArray or pa.Scalar
"""
if isinstance(value, pa.Scalar) or not is_list_like(value):
return cls._box_pa_scalar(value, pa_type)
return cls._box_pa_array(value, pa_type)
@classmethod
def _box_pa_scalar(cls, value, pa_type: pa.DataType | None = None) -> pa.Scalar:
"""
Box value into a pyarrow Scalar.
Parameters
----------
value : any
pa_type : pa.DataType | None
Returns
-------
pa.Scalar
"""
if isinstance(value, pa.Scalar):
pa_scalar = value
elif not is_list_like(value) and isna(value):
pa_scalar = pa.scalar(None, type=pa_type)
else:
# Workaround https://github.com/apache/arrow/issues/37291
if isinstance(value, Timedelta):
if pa_type is None:
pa_type = pa.duration(value.unit)
elif value.unit != pa_type.unit:
value = value.as_unit(pa_type.unit)
value = value._value
elif isinstance(value, Timestamp):
if pa_type is None:
pa_type = pa.timestamp(value.unit, tz=value.tz)
elif value.unit != pa_type.unit:
value = value.as_unit(pa_type.unit)
value = value._value
pa_scalar = pa.scalar(value, type=pa_type, from_pandas=True)
if pa_type is not None and pa_scalar.type != pa_type:
pa_scalar = pa_scalar.cast(pa_type)
return pa_scalar
@classmethod
def _box_pa_array(
cls, value, pa_type: pa.DataType | None = None, copy: bool = False
) -> pa.Array | pa.ChunkedArray:
"""
Box value into a pyarrow Array or ChunkedArray.
Parameters
----------
value : Sequence
pa_type : pa.DataType | None
Returns
-------
pa.Array or pa.ChunkedArray
"""
if isinstance(value, cls):
pa_array = value._pa_array
elif isinstance(value, (pa.Array, pa.ChunkedArray)):
pa_array = value
elif isinstance(value, BaseMaskedArray):
# GH 52625
if copy:
value = value.copy()
pa_array = value.__arrow_array__()
else:
if (
isinstance(value, np.ndarray)
and pa_type is not None
and (
pa.types.is_large_binary(pa_type)
or pa.types.is_large_string(pa_type)
)
):
# See https://github.com/apache/arrow/issues/35289
value = value.tolist()
elif copy and is_array_like(value):
# pa array should not get updated when numpy array is updated
value = value.copy()
if (
pa_type is not None
and pa.types.is_duration(pa_type)
and (not isinstance(value, np.ndarray) or value.dtype.kind not in "mi")
):
# Workaround https://github.com/apache/arrow/issues/37291
from pandas.core.tools.timedeltas import to_timedelta
value = to_timedelta(value, unit=pa_type.unit).as_unit(pa_type.unit)
value = value.to_numpy()
try:
pa_array = pa.array(value, type=pa_type, from_pandas=True)
except (pa.ArrowInvalid, pa.ArrowTypeError):
# GH50430: let pyarrow infer type, then cast
pa_array = pa.array(value, from_pandas=True)
if pa_type is None and pa.types.is_duration(pa_array.type):
# Workaround https://github.com/apache/arrow/issues/37291
from pandas.core.tools.timedeltas import to_timedelta
value = to_timedelta(value)
value = value.to_numpy()
pa_array = pa.array(value, type=pa_type, from_pandas=True)
if pa.types.is_duration(pa_array.type) and pa_array.null_count > 0:
# GH52843: upstream bug for duration types when originally
# constructed with data containing numpy NaT.
# https://github.com/apache/arrow/issues/35088
arr = cls(pa_array)
arr = arr.fillna(arr.dtype.na_value)
pa_array = arr._pa_array
if pa_type is not None and pa_array.type != pa_type:
if pa.types.is_dictionary(pa_type):
pa_array = pa_array.dictionary_encode()
if pa_array.type != pa_type:
pa_array = pa_array.cast(pa_type)
else:
try:
pa_array = pa_array.cast(pa_type)
except (pa.ArrowNotImplementedError, pa.ArrowTypeError):
if pa.types.is_string(pa_array.type) or pa.types.is_large_string(
pa_array.type
):
# TODO: Move logic in _from_sequence_of_strings into
# _box_pa_array
dtype = ArrowDtype(pa_type)
return cls._from_sequence_of_strings(
value, dtype=dtype
)._pa_array
else:
raise
return pa_array
def __getitem__(self, item: PositionalIndexer):
"""Select a subset of self.
Parameters
----------
item : int, slice, or ndarray
* int: The position in 'self' to get.
* slice: A slice object, where 'start', 'stop', and 'step' are
integers or None
* ndarray: A 1-d boolean NumPy ndarray the same length as 'self'
Returns
-------
item : scalar or ExtensionArray
Notes
-----
For scalar ``item``, return a scalar value suitable for the array's
type. This should be an instance of ``self.dtype.type``.
For slice ``key``, return an instance of ``ExtensionArray``, even
if the slice is length 0 or 1.
For a boolean mask, return an instance of ``ExtensionArray``, filtered
to the values where ``item`` is True.
"""
item = check_array_indexer(self, item)
if isinstance(item, np.ndarray):
if not len(item):
# Removable once we migrate StringDtype[pyarrow] to ArrowDtype[string]
if (
isinstance(self._dtype, StringDtype)
and self._dtype.storage == "pyarrow"
):
# TODO(infer_string) should this be large_string?
pa_dtype = pa.string()
else:
pa_dtype = self._dtype.pyarrow_dtype
return type(self)(pa.chunked_array([], type=pa_dtype))
elif item.dtype.kind in "iu":
return self.take(item)
elif item.dtype.kind == "b":
return type(self)(self._pa_array.filter(item))
else:
raise IndexError(
"Only integers, slices and integer or "
"boolean arrays are valid indices."
)
elif isinstance(item, tuple):
item = unpack_tuple_and_ellipses(item)
if item is Ellipsis:
# TODO: should be handled by pyarrow?
item = slice(None)
if is_scalar(item) and not is_integer(item):
# e.g. "foo" or 2.5
# exception message copied from numpy
raise IndexError(
r"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis "
r"(`None`) and integer or boolean arrays are valid indices"
)
# We are not an array indexer, so maybe e.g. a slice or integer
# indexer. We dispatch to pyarrow.
if isinstance(item, slice):
# Arrow bug https://github.com/apache/arrow/issues/38768
if item.start == item.stop:
pass
elif (
item.stop is not None
and item.stop < -len(self)
and item.step is not None
and item.step < 0
):
item = slice(item.start, None, item.step)
value = self._pa_array[item]
if isinstance(value, pa.ChunkedArray):
return type(self)(value)
else:
pa_type = self._pa_array.type
scalar = value.as_py()
if scalar is None:
return self._dtype.na_value
elif pa.types.is_timestamp(pa_type) and pa_type.unit != "ns":
# GH 53326
return Timestamp(scalar).as_unit(pa_type.unit)
elif pa.types.is_duration(pa_type) and pa_type.unit != "ns":
# GH 53326
return Timedelta(scalar).as_unit(pa_type.unit)
else:
return scalar
def __iter__(self) -> Iterator[Any]:
"""
Iterate over elements of the array.
"""
na_value = self._dtype.na_value
# GH 53326
pa_type = self._pa_array.type
box_timestamp = pa.types.is_timestamp(pa_type) and pa_type.unit != "ns"
box_timedelta = pa.types.is_duration(pa_type) and pa_type.unit != "ns"
for value in self._pa_array:
val = value.as_py()
if val is None:
yield na_value
elif box_timestamp:
yield Timestamp(val).as_unit(pa_type.unit)
elif box_timedelta:
yield Timedelta(val).as_unit(pa_type.unit)
else:
yield val
def __arrow_array__(self, type=None):
"""Convert myself to a pyarrow ChunkedArray."""
return self._pa_array
def __array__(
self, dtype: NpDtype | None = None, copy: bool | None = None
) -> np.ndarray:
"""Correctly construct numpy arrays when passed to `np.asarray()`."""
if copy is False:
# TODO: By using `zero_copy_only` it may be possible to implement this
raise ValueError(
"Unable to avoid copy while creating an array as requested."
)
elif copy is None:
# `to_numpy(copy=False)` has the meaning of NumPy `copy=None`.
copy = False
return self.to_numpy(dtype=dtype, copy=copy)
def __invert__(self) -> Self:
# This is a bit wise op for integer types
if pa.types.is_integer(self._pa_array.type):
return type(self)(pc.bit_wise_not(self._pa_array))
elif pa.types.is_string(self._pa_array.type) or pa.types.is_large_string(
self._pa_array.type
):
# Raise TypeError instead of pa.ArrowNotImplementedError
raise TypeError("__invert__ is not supported for string dtypes")
else:
return type(self)(pc.invert(self._pa_array))
def __neg__(self) -> Self:
try:
return type(self)(pc.negate_checked(self._pa_array))
except pa.ArrowNotImplementedError as err:
raise TypeError(
f"unary '-' not supported for dtype '{self.dtype}'"
) from err
def __pos__(self) -> Self:
return type(self)(self._pa_array)
def __abs__(self) -> Self:
return type(self)(pc.abs_checked(self._pa_array))
# GH 42600: __getstate__/__setstate__ not necessary once
# https://issues.apache.org/jira/browse/ARROW-10739 is addressed
def __getstate__(self):
state = self.__dict__.copy()
state["_pa_array"] = self._pa_array.combine_chunks()
return state
def __setstate__(self, state) -> None:
if "_data" in state:
data = state.pop("_data")
else:
data = state["_pa_array"]
state["_pa_array"] = pa.chunked_array(data)
self.__dict__.update(state)
def _cmp_method(self, other, op) -> ArrowExtensionArray:
pc_func = ARROW_CMP_FUNCS[op.__name__]
if isinstance(
other, (ArrowExtensionArray, np.ndarray, list, BaseMaskedArray)
) or isinstance(getattr(other, "dtype", None), CategoricalDtype):
try:
result = pc_func(self._pa_array, self._box_pa(other))
except pa.ArrowNotImplementedError:
# TODO: could this be wrong if other is object dtype?
# in which case we need to operate pointwise?
result = ops.invalid_comparison(self, other, op)
result = pa.array(result, type=pa.bool_())
elif is_scalar(other):
try:
result = pc_func(self._pa_array, self._box_pa(other))
except (pa.lib.ArrowNotImplementedError, pa.lib.ArrowInvalid):
mask = isna(self) | isna(other)
valid = ~mask
result = np.zeros(len(self), dtype="bool")
np_array = np.array(self)
try:
result[valid] = op(np_array[valid], other)
except TypeError:
result = ops.invalid_comparison(self, other, op)
result = pa.array(result, type=pa.bool_())
result = pc.if_else(valid, result, None)
else:
raise NotImplementedError(
f"{op.__name__} not implemented for {type(other)}"
)
return ArrowExtensionArray(result)
def _op_method_error_message(self, other, op) -> str:
if hasattr(other, "dtype"):
other_type = f"dtype '{other.dtype}'"
else:
other_type = f"object of type {type(other)}"
return (
f"operation '{op.__name__}' not supported for "
f"dtype '{self.dtype}' with {other_type}"
)
def _evaluate_op_method(self, other, op, arrow_funcs) -> Self:
pa_type = self._pa_array.type
other_original = other
other = self._box_pa(other)
if (
pa.types.is_string(pa_type)
or pa.types.is_large_string(pa_type)
or pa.types.is_binary(pa_type)
):
if op in [operator.add, roperator.radd]:
sep = pa.scalar("", type=pa_type)
try:
if op is operator.add:
result = pc.binary_join_element_wise(self._pa_array, other, sep)
elif op is roperator.radd:
result = pc.binary_join_element_wise(other, self._pa_array, sep)
except pa.ArrowNotImplementedError as err:
raise TypeError(
self._op_method_error_message(other_original, op)
) from err
return type(self)(result)
elif op in [operator.mul, roperator.rmul]:
binary = self._pa_array
integral = other
if not pa.types.is_integer(integral.type):
raise TypeError("Can only string multiply by an integer.")
pa_integral = pc.if_else(pc.less(integral, 0), 0, integral)
result = pc.binary_repeat(binary, pa_integral)
return type(self)(result)
elif (
pa.types.is_string(other.type)
or pa.types.is_binary(other.type)
or pa.types.is_large_string(other.type)
) and op in [operator.mul, roperator.rmul]:
binary = other
integral = self._pa_array
if not pa.types.is_integer(integral.type):
raise TypeError("Can only string multiply by an integer.")
pa_integral = pc.if_else(pc.less(integral, 0), 0, integral)
result = pc.binary_repeat(binary, pa_integral)
return type(self)(result)
if (
isinstance(other, pa.Scalar)
and pc.is_null(other).as_py()
and op.__name__ in ARROW_LOGICAL_FUNCS
):
# pyarrow kleene ops require null to be typed
other = other.cast(pa_type)
pc_func = arrow_funcs[op.__name__]
if pc_func is NotImplemented:
if pa.types.is_string(pa_type) or pa.types.is_large_string(pa_type):
raise TypeError(self._op_method_error_message(other_original, op))
raise NotImplementedError(f"{op.__name__} not implemented.")
try:
result = pc_func(self._pa_array, other)
except pa.ArrowNotImplementedError as err:
raise TypeError(self._op_method_error_message(other_original, op)) from err
return type(self)(result)
def _logical_method(self, other, op) -> Self:
# For integer types `^`, `|`, `&` are bitwise operators and return
# integer types. Otherwise these are boolean ops.
if pa.types.is_integer(self._pa_array.type):
return self._evaluate_op_method(other, op, ARROW_BIT_WISE_FUNCS)
else:
return self._evaluate_op_method(other, op, ARROW_LOGICAL_FUNCS)
def _arith_method(self, other, op) -> Self:
return self._evaluate_op_method(other, op, ARROW_ARITHMETIC_FUNCS)
def equals(self, other) -> bool:
if not isinstance(other, ArrowExtensionArray):
return False
# I'm told that pyarrow makes __eq__ behave like pandas' equals;
# TODO: is this documented somewhere?
return self._pa_array == other._pa_array
@property
def dtype(self) -> ArrowDtype:
"""
An instance of 'ExtensionDtype'.
"""
return self._dtype
@property
def nbytes(self) -> int:
"""
The number of bytes needed to store this object in memory.
"""
return self._pa_array.nbytes
def __len__(self) -> int:
"""
Length of this array.
Returns
-------
length : int
"""
return len(self._pa_array)
def __contains__(self, key) -> bool:
# https://github.com/pandas-dev/pandas/pull/51307#issuecomment-1426372604
if isna(key) and key is not self.dtype.na_value:
if self.dtype.kind == "f" and lib.is_float(key):
return pc.any(pc.is_nan(self._pa_array)).as_py()
# e.g. date or timestamp types we do not allow None here to match pd.NA
return False
# TODO: maybe complex? object?
return bool(super().__contains__(key))
@property
def _hasna(self) -> bool:
return self._pa_array.null_count > 0
def isna(self) -> npt.NDArray[np.bool_]:
"""
Boolean NumPy array indicating if each value is missing.
This should return a 1-D array the same length as 'self'.
"""
# GH51630: fast paths
null_count = self._pa_array.null_count
if null_count == 0:
return np.zeros(len(self), dtype=np.bool_)
elif null_count == len(self):
return np.ones(len(self), dtype=np.bool_)
return self._pa_array.is_null().to_numpy()
@overload
def any(self, *, skipna: Literal[True] = ..., **kwargs) -> bool: ...
@overload
def any(self, *, skipna: bool, **kwargs) -> bool | NAType: ...
def any(self, *, skipna: bool = True, **kwargs) -> bool | NAType:
"""
Return whether any element is truthy.
Returns False unless there is at least one element that is truthy.
By default, NAs are skipped. If ``skipna=False`` is specified and
missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
is used as for logical operations.
Parameters
----------
skipna : bool, default True
Exclude NA values. If the entire array is NA and `skipna` is
True, then the result will be False, as for an empty array.
If `skipna` is False, the result will still be True if there is
at least one element that is truthy, otherwise NA will be returned
if there are NA's present.
Returns
-------
bool or :attr:`pandas.NA`
See Also
--------
ArrowExtensionArray.all : Return whether all elements are truthy.
Examples
--------
The result indicates whether any element is truthy (and by default
skips NAs):
>>> pd.array([True, False, True], dtype="boolean[pyarrow]").any()
True
>>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any()
True
>>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any()
False
>>> pd.array([], dtype="boolean[pyarrow]").any()
False
>>> pd.array([pd.NA], dtype="boolean[pyarrow]").any()
False
>>> pd.array([pd.NA], dtype="float64[pyarrow]").any()
False
With ``skipna=False``, the result can be NA if this is logically
required (whether ``pd.NA`` is True or False influences the result):
>>> pd.array([True, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
True
>>> pd.array([1, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
True
>>> pd.array([False, False, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
<NA>
>>> pd.array([0, 0, pd.NA], dtype="boolean[pyarrow]").any(skipna=False)
<NA>
"""
return self._reduce("any", skipna=skipna, **kwargs)
@overload
def all(self, *, skipna: Literal[True] = ..., **kwargs) -> bool: ...
@overload
def all(self, *, skipna: bool, **kwargs) -> bool | NAType: ...
def all(self, *, skipna: bool = True, **kwargs) -> bool | NAType:
"""
Return whether all elements are truthy.
Returns True unless there is at least one element that is falsey.
By default, NAs are skipped. If ``skipna=False`` is specified and
missing values are present, similar :ref:`Kleene logic <boolean.kleene>`
is used as for logical operations.
Parameters
----------
skipna : bool, default True
Exclude NA values. If the entire array is NA and `skipna` is
True, then the result will be True, as for an empty array.
If `skipna` is False, the result will still be False if there is
at least one element that is falsey, otherwise NA will be returned
if there are NA's present.
Returns
-------
bool or :attr:`pandas.NA`
See Also
--------
ArrowExtensionArray.any : Return whether any element is truthy.
Examples
--------
The result indicates whether all elements are truthy (and by default
skips NAs):