-
-
Notifications
You must be signed in to change notification settings - Fork 18.2k
/
Copy pathtest_arrow.py
3513 lines (2975 loc) · 118 KB
/
test_arrow.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
"""
This file contains a minimal set of tests for compliance with the extension
array interface test suite, and should contain no other tests.
The test suite for the full functionality of the array is located in
`pandas/tests/arrays/`.
The tests in this file are inherited from the BaseExtensionTests, and only
minimal tweaks should be applied to get the tests passing (by overwriting a
parent method).
Additional tests should either be added to one of the BaseExtensionTests
classes (if they are relevant for the extension interface for all dtypes), or
be added to the array-specific tests in `pandas/tests/arrays/`.
"""
from __future__ import annotations
from datetime import (
date,
datetime,
time,
timedelta,
)
from decimal import Decimal
from io import (
BytesIO,
StringIO,
)
import operator
import pickle
import re
import sys
import numpy as np
import pytest
from pandas._libs import lib
from pandas._libs.tslibs import timezones
from pandas.compat import (
PY311,
PY312,
is_ci_environment,
is_platform_windows,
pa_version_under11p0,
pa_version_under13p0,
pa_version_under14p0,
)
import pandas.util._test_decorators as td
from pandas.core.dtypes.dtypes import (
ArrowDtype,
CategoricalDtypeType,
)
import pandas as pd
import pandas._testing as tm
from pandas.api.extensions import no_default
from pandas.api.types import (
is_bool_dtype,
is_datetime64_any_dtype,
is_float_dtype,
is_integer_dtype,
is_numeric_dtype,
is_signed_integer_dtype,
is_string_dtype,
is_unsigned_integer_dtype,
)
from pandas.tests.extension import base
pa = pytest.importorskip("pyarrow")
from pandas.core.arrays.arrow.array import ArrowExtensionArray
from pandas.core.arrays.arrow.extension_types import ArrowPeriodType
def _require_timezone_database(request):
if is_platform_windows() and is_ci_environment():
mark = pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason=(
"TODO: Set ARROW_TIMEZONE_DATABASE environment variable "
"on CI to path to the tzdata for pyarrow."
),
)
request.applymarker(mark)
@pytest.fixture(params=tm.ALL_PYARROW_DTYPES, ids=str)
def dtype(request):
return ArrowDtype(pyarrow_dtype=request.param)
@pytest.fixture
def data(dtype):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
data = [True, False] * 4 + [None] + [True, False] * 44 + [None] + [True, False]
elif pa.types.is_floating(pa_dtype):
data = [1.0, 0.0] * 4 + [None] + [-2.0, -1.0] * 44 + [None] + [0.5, 99.5]
elif pa.types.is_signed_integer(pa_dtype):
data = [1, 0] * 4 + [None] + [-2, -1] * 44 + [None] + [1, 99]
elif pa.types.is_unsigned_integer(pa_dtype):
data = [1, 0] * 4 + [None] + [2, 1] * 44 + [None] + [1, 99]
elif pa.types.is_decimal(pa_dtype):
data = (
[Decimal("1"), Decimal("0.0")] * 4
+ [None]
+ [Decimal("-2.0"), Decimal("-1.0")] * 44
+ [None]
+ [Decimal("0.5"), Decimal("33.123")]
)
elif pa.types.is_date(pa_dtype):
data = (
[date(2022, 1, 1), date(1999, 12, 31)] * 4
+ [None]
+ [date(2022, 1, 1), date(2022, 1, 1)] * 44
+ [None]
+ [date(1999, 12, 31), date(1999, 12, 31)]
)
elif pa.types.is_timestamp(pa_dtype):
data = (
[datetime(2020, 1, 1, 1, 1, 1, 1), datetime(1999, 1, 1, 1, 1, 1, 1)] * 4
+ [None]
+ [datetime(2020, 1, 1, 1), datetime(1999, 1, 1, 1)] * 44
+ [None]
+ [datetime(2020, 1, 1), datetime(1999, 1, 1)]
)
elif pa.types.is_duration(pa_dtype):
data = (
[timedelta(1), timedelta(1, 1)] * 4
+ [None]
+ [timedelta(-1), timedelta(0)] * 44
+ [None]
+ [timedelta(-10), timedelta(10)]
)
elif pa.types.is_time(pa_dtype):
data = (
[time(12, 0), time(0, 12)] * 4
+ [None]
+ [time(0, 0), time(1, 1)] * 44
+ [None]
+ [time(0, 5), time(5, 0)]
)
elif pa.types.is_string(pa_dtype):
data = ["a", "b"] * 4 + [None] + ["1", "2"] * 44 + [None] + ["!", ">"]
elif pa.types.is_binary(pa_dtype):
data = [b"a", b"b"] * 4 + [None] + [b"1", b"2"] * 44 + [None] + [b"!", b">"]
else:
raise NotImplementedError
return pd.array(data, dtype=dtype)
@pytest.fixture
def data_missing(data):
"""Length-2 array with [NA, Valid]"""
return type(data)._from_sequence([None, data[0]], dtype=data.dtype)
@pytest.fixture(params=["data", "data_missing"])
def all_data(request, data, data_missing):
"""Parametrized fixture returning 'data' or 'data_missing' integer arrays.
Used to test dtype conversion with and without missing values.
"""
if request.param == "data":
return data
elif request.param == "data_missing":
return data_missing
@pytest.fixture
def data_for_grouping(dtype):
"""
Data for factorization, grouping, and unique tests.
Expected to be like [B, B, NA, NA, A, A, B, C]
Where A < B < C and NA is missing
"""
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
A = False
B = True
C = True
elif pa.types.is_floating(pa_dtype):
A = -1.1
B = 0.0
C = 1.1
elif pa.types.is_signed_integer(pa_dtype):
A = -1
B = 0
C = 1
elif pa.types.is_unsigned_integer(pa_dtype):
A = 0
B = 1
C = 10
elif pa.types.is_date(pa_dtype):
A = date(1999, 12, 31)
B = date(2010, 1, 1)
C = date(2022, 1, 1)
elif pa.types.is_timestamp(pa_dtype):
A = datetime(1999, 1, 1, 1, 1, 1, 1)
B = datetime(2020, 1, 1)
C = datetime(2020, 1, 1, 1)
elif pa.types.is_duration(pa_dtype):
A = timedelta(-1)
B = timedelta(0)
C = timedelta(1, 4)
elif pa.types.is_time(pa_dtype):
A = time(0, 0)
B = time(0, 12)
C = time(12, 12)
elif pa.types.is_string(pa_dtype):
A = "a"
B = "b"
C = "c"
elif pa.types.is_binary(pa_dtype):
A = b"a"
B = b"b"
C = b"c"
elif pa.types.is_decimal(pa_dtype):
A = Decimal("-1.1")
B = Decimal("0.0")
C = Decimal("1.1")
else:
raise NotImplementedError
return pd.array([B, B, None, None, A, A, B, C], dtype=dtype)
@pytest.fixture
def data_for_sorting(data_for_grouping):
"""
Length-3 array with a known sort order.
This should be three items [B, C, A] with
A < B < C
"""
return type(data_for_grouping)._from_sequence(
[data_for_grouping[0], data_for_grouping[7], data_for_grouping[4]],
dtype=data_for_grouping.dtype,
)
@pytest.fixture
def data_missing_for_sorting(data_for_grouping):
"""
Length-3 array with a known sort order.
This should be three items [B, NA, A] with
A < B and NA missing.
"""
return type(data_for_grouping)._from_sequence(
[data_for_grouping[0], data_for_grouping[2], data_for_grouping[4]],
dtype=data_for_grouping.dtype,
)
@pytest.fixture
def data_for_twos(data):
"""Length-100 array in which all the elements are two."""
pa_dtype = data.dtype.pyarrow_dtype
if (
pa.types.is_integer(pa_dtype)
or pa.types.is_floating(pa_dtype)
or pa.types.is_decimal(pa_dtype)
or pa.types.is_duration(pa_dtype)
):
return pd.array([2] * 100, dtype=data.dtype)
# tests will be xfailed where 2 is not a valid scalar for pa_dtype
return data
# TODO: skip otherwise?
class TestArrowArray(base.ExtensionTests):
def test_compare_scalar(self, data, comparison_op):
ser = pd.Series(data)
self._compare_other(ser, data, comparison_op, data[0])
@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data_missing, na_action):
if data_missing.dtype.kind in "mM":
result = data_missing.map(lambda x: x, na_action=na_action)
expected = data_missing.to_numpy(dtype=object)
tm.assert_numpy_array_equal(result, expected)
else:
result = data_missing.map(lambda x: x, na_action=na_action)
if data_missing.dtype == "float32[pyarrow]":
# map roundtrips through objects, which converts to float64
expected = data_missing.to_numpy(dtype="float64", na_value=np.nan)
else:
expected = data_missing.to_numpy()
tm.assert_numpy_array_equal(result, expected)
def test_astype_str(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_binary(pa_dtype):
request.applymarker(
pytest.mark.xfail(
reason=f"For {pa_dtype} .astype(str) decodes.",
)
)
elif (
pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None
) or pa.types.is_duration(pa_dtype):
request.applymarker(
pytest.mark.xfail(
reason="pd.Timestamp/pd.Timedelta repr different from numpy repr",
)
)
super().test_astype_str(data)
@pytest.mark.parametrize(
"nullable_string_dtype",
[
"string[python]",
pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
],
)
def test_astype_string(self, data, nullable_string_dtype, request):
pa_dtype = data.dtype.pyarrow_dtype
if (
pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None
) or pa.types.is_duration(pa_dtype):
request.applymarker(
pytest.mark.xfail(
reason="pd.Timestamp/pd.Timedelta repr different from numpy repr",
)
)
super().test_astype_string(data, nullable_string_dtype)
def test_from_dtype(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_string(pa_dtype) or pa.types.is_decimal(pa_dtype):
if pa.types.is_string(pa_dtype):
reason = "ArrowDtype(pa.string()) != StringDtype('pyarrow')"
else:
reason = f"pyarrow.type_for_alias cannot infer {pa_dtype}"
request.applymarker(
pytest.mark.xfail(
reason=reason,
)
)
super().test_from_dtype(data)
def test_from_sequence_pa_array(self, data):
# https://github.com/pandas-dev/pandas/pull/47034#discussion_r955500784
# data._pa_array = pa.ChunkedArray
result = type(data)._from_sequence(data._pa_array, dtype=data.dtype)
tm.assert_extension_array_equal(result, data)
assert isinstance(result._pa_array, pa.ChunkedArray)
result = type(data)._from_sequence(
data._pa_array.combine_chunks(), dtype=data.dtype
)
tm.assert_extension_array_equal(result, data)
assert isinstance(result._pa_array, pa.ChunkedArray)
def test_from_sequence_pa_array_notimplemented(self, request):
dtype = ArrowDtype(pa.month_day_nano_interval())
with pytest.raises(NotImplementedError, match="Converting strings to"):
ArrowExtensionArray._from_sequence_of_strings(["12-1"], dtype=dtype)
def test_from_sequence_of_strings_pa_array(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_time64(pa_dtype) and pa_dtype.equals("time64[ns]") and not PY311:
request.applymarker(
pytest.mark.xfail(
reason="Nanosecond time parsing not supported.",
)
)
elif pa_version_under11p0 and (
pa.types.is_duration(pa_dtype) or pa.types.is_decimal(pa_dtype)
):
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowNotImplementedError,
reason=f"pyarrow doesn't support parsing {pa_dtype}",
)
)
elif pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
_require_timezone_database(request)
pa_array = data._pa_array.cast(pa.string())
result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
tm.assert_extension_array_equal(result, data)
pa_array = pa_array.combine_chunks()
result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
tm.assert_extension_array_equal(result, data)
def check_accumulate(self, ser, op_name, skipna):
result = getattr(ser, op_name)(skipna=skipna)
pa_type = ser.dtype.pyarrow_dtype
if pa.types.is_temporal(pa_type):
# Just check that we match the integer behavior.
if pa_type.bit_width == 32:
int_type = "int32[pyarrow]"
else:
int_type = "int64[pyarrow]"
ser = ser.astype(int_type)
result = result.astype(int_type)
result = result.astype("Float64")
expected = getattr(ser.astype("Float64"), op_name)(skipna=skipna)
tm.assert_series_equal(result, expected, check_dtype=False)
def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool:
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
# attribute "pyarrow_dtype"
pa_type = ser.dtype.pyarrow_dtype # type: ignore[union-attr]
if (
pa.types.is_string(pa_type)
or pa.types.is_binary(pa_type)
or pa.types.is_decimal(pa_type)
):
if op_name in ["cumsum", "cumprod", "cummax", "cummin"]:
return False
elif pa.types.is_boolean(pa_type):
if op_name in ["cumprod", "cummax", "cummin"]:
return False
elif pa.types.is_temporal(pa_type):
if op_name == "cumsum" and not pa.types.is_duration(pa_type):
return False
elif op_name == "cumprod":
return False
return True
@pytest.mark.parametrize("skipna", [True, False])
def test_accumulate_series(self, data, all_numeric_accumulations, skipna, request):
pa_type = data.dtype.pyarrow_dtype
op_name = all_numeric_accumulations
ser = pd.Series(data)
if not self._supports_accumulation(ser, op_name):
# The base class test will check that we raise
return super().test_accumulate_series(
data, all_numeric_accumulations, skipna
)
if pa_version_under13p0 and all_numeric_accumulations != "cumsum":
# xfailing takes a long time to run because pytest
# renders the exception messages even when not showing them
opt = request.config.option
if opt.markexpr and "not slow" in opt.markexpr:
pytest.skip(
f"{all_numeric_accumulations} not implemented for pyarrow < 9"
)
mark = pytest.mark.xfail(
reason=f"{all_numeric_accumulations} not implemented for pyarrow < 9"
)
request.applymarker(mark)
elif all_numeric_accumulations == "cumsum" and (
pa.types.is_boolean(pa_type) or pa.types.is_decimal(pa_type)
):
request.applymarker(
pytest.mark.xfail(
reason=f"{all_numeric_accumulations} not implemented for {pa_type}",
raises=NotImplementedError,
)
)
self.check_accumulate(ser, op_name, skipna)
def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool:
dtype = ser.dtype
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has
# no attribute "pyarrow_dtype"
pa_dtype = dtype.pyarrow_dtype # type: ignore[union-attr]
if pa.types.is_temporal(pa_dtype) and op_name in [
"sum",
"var",
"skew",
"kurt",
"prod",
]:
if pa.types.is_duration(pa_dtype) and op_name in ["sum"]:
# summing timedeltas is one case that *is* well-defined
pass
else:
return False
elif (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
) and op_name in [
"sum",
"mean",
"median",
"prod",
"std",
"sem",
"var",
"skew",
"kurt",
]:
return False
if (
pa.types.is_temporal(pa_dtype)
and not pa.types.is_duration(pa_dtype)
and op_name in ["any", "all"]
):
# xref GH#34479 we support this in our non-pyarrow datetime64 dtypes,
# but it isn't obvious we _should_. For now, we keep the pyarrow
# behavior which does not support this.
return False
return True
def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
# attribute "pyarrow_dtype"
pa_dtype = ser.dtype.pyarrow_dtype # type: ignore[union-attr]
if pa.types.is_integer(pa_dtype) or pa.types.is_floating(pa_dtype):
alt = ser.astype("Float64")
else:
# TODO: in the opposite case, aren't we testing... nothing? For
# e.g. date/time dtypes trying to calculate 'expected' by converting
# to object will raise for mean, std etc
alt = ser
# TODO: in the opposite case, aren't we testing... nothing?
if op_name == "count":
result = getattr(ser, op_name)()
expected = getattr(alt, op_name)()
else:
result = getattr(ser, op_name)(skipna=skipna)
expected = getattr(alt, op_name)(skipna=skipna)
tm.assert_almost_equal(result, expected)
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request):
dtype = data.dtype
pa_dtype = dtype.pyarrow_dtype
xfail_mark = pytest.mark.xfail(
raises=TypeError,
reason=(
f"{all_numeric_reductions} is not implemented in "
f"pyarrow={pa.__version__} for {pa_dtype}"
),
)
if all_numeric_reductions in {"skew", "kurt"} and (
dtype._is_numeric or dtype.kind == "b"
):
request.applymarker(xfail_mark)
elif pa.types.is_boolean(pa_dtype) and all_numeric_reductions in {
"sem",
"std",
"var",
"median",
}:
request.applymarker(xfail_mark)
super().test_reduce_series_numeric(data, all_numeric_reductions, skipna)
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_boolean(
self, data, all_boolean_reductions, skipna, na_value, request
):
pa_dtype = data.dtype.pyarrow_dtype
xfail_mark = pytest.mark.xfail(
raises=TypeError,
reason=(
f"{all_boolean_reductions} is not implemented in "
f"pyarrow={pa.__version__} for {pa_dtype}"
),
)
if pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype):
# We *might* want to make this behave like the non-pyarrow cases,
# but have not yet decided.
request.applymarker(xfail_mark)
return super().test_reduce_series_boolean(data, all_boolean_reductions, skipna)
def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool):
if op_name in ["max", "min"]:
cmp_dtype = arr.dtype
elif arr.dtype.name == "decimal128(7, 3)[pyarrow]":
if op_name not in ["median", "var", "std"]:
cmp_dtype = arr.dtype
else:
cmp_dtype = "float64[pyarrow]"
elif op_name in ["median", "var", "std", "mean", "skew"]:
cmp_dtype = "float64[pyarrow]"
else:
cmp_dtype = {
"i": "int64[pyarrow]",
"u": "uint64[pyarrow]",
"f": "float64[pyarrow]",
}[arr.dtype.kind]
return cmp_dtype
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_frame(self, data, all_numeric_reductions, skipna, request):
op_name = all_numeric_reductions
if op_name == "skew":
if data.dtype._is_numeric:
mark = pytest.mark.xfail(reason="skew not implemented")
request.applymarker(mark)
return super().test_reduce_frame(data, all_numeric_reductions, skipna)
@pytest.mark.parametrize("typ", ["int64", "uint64", "float64"])
def test_median_not_approximate(self, typ):
# GH 52679
result = pd.Series([1, 2], dtype=f"{typ}[pyarrow]").median()
assert result == 1.5
def test_in_numeric_groupby(self, data_for_grouping):
dtype = data_for_grouping.dtype
if is_string_dtype(dtype):
df = pd.DataFrame(
{
"A": [1, 1, 2, 2, 3, 3, 1, 4],
"B": data_for_grouping,
"C": [1, 1, 1, 1, 1, 1, 1, 1],
}
)
expected = pd.Index(["C"])
msg = re.escape(f"agg function failed [how->sum,dtype->{dtype}")
with pytest.raises(TypeError, match=msg):
df.groupby("A").sum()
result = df.groupby("A").sum(numeric_only=True).columns
tm.assert_index_equal(result, expected)
else:
super().test_in_numeric_groupby(data_for_grouping)
def test_construct_from_string_own_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_decimal(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
)
)
if pa.types.is_string(pa_dtype):
# We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
msg = r"string\[pyarrow\] should be constructed by StringDtype"
with pytest.raises(TypeError, match=msg):
dtype.construct_from_string(dtype.name)
return
super().test_construct_from_string_own_name(dtype)
def test_is_dtype_from_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_string(pa_dtype):
# We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
assert not type(dtype).is_dtype(dtype.name)
else:
if pa.types.is_decimal(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
)
)
super().test_is_dtype_from_name(dtype)
def test_construct_from_string_another_type_raises(self, dtype):
msg = r"'another_type' must end with '\[pyarrow\]'"
with pytest.raises(TypeError, match=msg):
type(dtype).construct_from_string("another_type")
def test_get_common_dtype(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if (
pa.types.is_date(pa_dtype)
or pa.types.is_time(pa_dtype)
or (pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None)
or pa.types.is_binary(pa_dtype)
or pa.types.is_decimal(pa_dtype)
):
request.applymarker(
pytest.mark.xfail(
reason=(
f"{pa_dtype} does not have associated numpy "
f"dtype findable by find_common_type"
)
)
)
super().test_get_common_dtype(dtype)
def test_is_not_string_type(self, dtype):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_string(pa_dtype):
assert is_string_dtype(dtype)
else:
super().test_is_not_string_type(dtype)
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views.", run=False
)
def test_view(self, data):
super().test_view(data)
def test_fillna_no_op_returns_copy(self, data):
data = data[~data.isna()]
valid = data[0]
result = data.fillna(valid)
assert result is not data
tm.assert_extension_array_equal(result, data)
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
)
def test_transpose(self, data):
super().test_transpose(data)
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
)
def test_setitem_preserves_views(self, data):
super().test_setitem_preserves_views(data)
@pytest.mark.parametrize("dtype_backend", ["pyarrow", no_default])
@pytest.mark.parametrize("engine", ["c", "python"])
def test_EA_types(self, engine, data, dtype_backend, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_decimal(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"Parameterized types {pa_dtype} not supported.",
)
)
elif pa.types.is_timestamp(pa_dtype) and pa_dtype.unit in ("us", "ns"):
request.applymarker(
pytest.mark.xfail(
raises=ValueError,
reason="https://github.com/pandas-dev/pandas/issues/49767",
)
)
elif pa.types.is_binary(pa_dtype):
request.applymarker(
pytest.mark.xfail(reason="CSV parsers don't correctly handle binary")
)
df = pd.DataFrame({"with_dtype": pd.Series(data, dtype=str(data.dtype))})
csv_output = df.to_csv(index=False, na_rep=np.nan)
if pa.types.is_binary(pa_dtype):
csv_output = BytesIO(csv_output)
else:
csv_output = StringIO(csv_output)
result = pd.read_csv(
csv_output,
dtype={"with_dtype": str(data.dtype)},
engine=engine,
dtype_backend=dtype_backend,
)
expected = df
tm.assert_frame_equal(result, expected)
def test_invert(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if not (
pa.types.is_boolean(pa_dtype)
or pa.types.is_integer(pa_dtype)
or pa.types.is_string(pa_dtype)
):
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowNotImplementedError,
reason=f"pyarrow.compute.invert does support {pa_dtype}",
)
)
if PY312 and pa.types.is_boolean(pa_dtype):
with tm.assert_produces_warning(
DeprecationWarning, match="Bitwise inversion", check_stacklevel=False
):
super().test_invert(data)
else:
super().test_invert(data)
@pytest.mark.parametrize("periods", [1, -2])
def test_diff(self, data, periods, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_unsigned_integer(pa_dtype) and periods == 1:
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason=(
f"diff with {pa_dtype} and periods={periods} will overflow"
),
)
)
super().test_diff(data, periods)
def test_value_counts_returns_pyarrow_int64(self, data):
# GH 51462
data = data[:10]
result = data.value_counts()
assert result.dtype == ArrowDtype(pa.int64())
_combine_le_expected_dtype = "bool[pyarrow]"
divmod_exc = NotImplementedError
def get_op_from_name(self, op_name):
short_opname = op_name.strip("_")
if short_opname == "rtruediv":
# use the numpy version that won't raise on division by zero
def rtruediv(x, y):
return np.divide(y, x)
return rtruediv
elif short_opname == "rfloordiv":
return lambda x, y: np.floor_divide(y, x)
return tm.get_op_from_name(op_name)
def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
# BaseOpsUtil._combine can upcast expected dtype
# (because it generates expected on python scalars)
# while ArrowExtensionArray maintains original type
expected = pointwise_result
if op_name in ["eq", "ne", "lt", "le", "gt", "ge"]:
return pointwise_result.astype("boolean[pyarrow]")
was_frame = False
if isinstance(expected, pd.DataFrame):
was_frame = True
expected_data = expected.iloc[:, 0]
original_dtype = obj.iloc[:, 0].dtype
else:
expected_data = expected
original_dtype = obj.dtype
orig_pa_type = original_dtype.pyarrow_dtype
if not was_frame and isinstance(other, pd.Series):
# i.e. test_arith_series_with_array
if not (
pa.types.is_floating(orig_pa_type)
or (
pa.types.is_integer(orig_pa_type)
and op_name not in ["__truediv__", "__rtruediv__"]
)
or pa.types.is_duration(orig_pa_type)
or pa.types.is_timestamp(orig_pa_type)
or pa.types.is_date(orig_pa_type)
or pa.types.is_decimal(orig_pa_type)
):
# base class _combine always returns int64, while
# ArrowExtensionArray does not upcast
return expected
elif not (
(op_name == "__floordiv__" and pa.types.is_integer(orig_pa_type))
or pa.types.is_duration(orig_pa_type)
or pa.types.is_timestamp(orig_pa_type)
or pa.types.is_date(orig_pa_type)
or pa.types.is_decimal(orig_pa_type)
):
# base class _combine always returns int64, while
# ArrowExtensionArray does not upcast
return expected
pa_expected = pa.array(expected_data._values)
if pa.types.is_duration(pa_expected.type):
if pa.types.is_date(orig_pa_type):
if pa.types.is_date64(orig_pa_type):
# TODO: why is this different vs date32?
unit = "ms"
else:
unit = "s"
else:
# pyarrow sees sequence of datetime/timedelta objects and defaults
# to "us" but the non-pointwise op retains unit
# timestamp or duration
unit = orig_pa_type.unit
if type(other) in [datetime, timedelta] and unit in ["s", "ms"]:
# pydatetime/pytimedelta objects have microsecond reso, so we
# take the higher reso of the original and microsecond. Note
# this matches what we would do with DatetimeArray/TimedeltaArray
unit = "us"
pa_expected = pa_expected.cast(f"duration[{unit}]")
elif pa.types.is_decimal(pa_expected.type) and pa.types.is_decimal(
orig_pa_type
):
# decimal precision can resize in the result type depending on data
# just compare the float values
alt = getattr(obj, op_name)(other)
alt_dtype = tm.get_dtype(alt)
assert isinstance(alt_dtype, ArrowDtype)
if op_name == "__pow__" and isinstance(other, Decimal):
# TODO: would it make more sense to retain Decimal here?
alt_dtype = ArrowDtype(pa.float64())
elif (
op_name == "__pow__"
and isinstance(other, pd.Series)
and other.dtype == original_dtype
):
# TODO: would it make more sense to retain Decimal here?
alt_dtype = ArrowDtype(pa.float64())
else:
assert pa.types.is_decimal(alt_dtype.pyarrow_dtype)
return expected.astype(alt_dtype)
else:
pa_expected = pa_expected.cast(orig_pa_type)
pd_expected = type(expected_data._values)(pa_expected)
if was_frame:
expected = pd.DataFrame(
pd_expected, index=expected.index, columns=expected.columns
)
else:
expected = pd.Series(pd_expected)
return expected
def _is_temporal_supported(self, opname, pa_dtype):
return (
(
opname in ("__add__", "__radd__")
or (
opname
in ("__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__")
and not pa_version_under14p0
)
)
and pa.types.is_duration(pa_dtype)
or opname in ("__sub__", "__rsub__")
and pa.types.is_temporal(pa_dtype)
)
def _get_expected_exception(
self, op_name: str, obj, other
) -> type[Exception] | None:
if op_name in ("__divmod__", "__rdivmod__"):
return self.divmod_exc
dtype = tm.get_dtype(obj)
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
# attribute "pyarrow_dtype"
pa_dtype = dtype.pyarrow_dtype # type: ignore[union-attr]
arrow_temporal_supported = self._is_temporal_supported(op_name, pa_dtype)
if op_name in {
"__mod__",
"__rmod__",
}:
exc = NotImplementedError
elif arrow_temporal_supported:
exc = None
elif op_name in ["__add__", "__radd__"] and (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
):
exc = None
elif not (
pa.types.is_floating(pa_dtype)
or pa.types.is_integer(pa_dtype)
or pa.types.is_decimal(pa_dtype)
):
# TODO: in many of these cases, e.g. non-duration temporal,
# these will *never* be allowed. Would it make more sense to
# re-raise as TypeError, more consistent with non-pyarrow cases?
exc = pa.ArrowNotImplementedError
else:
exc = None
return exc
def _get_arith_xfail_marker(self, opname, pa_dtype):
mark = None
arrow_temporal_supported = self._is_temporal_supported(opname, pa_dtype)
if opname == "__rpow__" and (
pa.types.is_floating(pa_dtype)
or pa.types.is_integer(pa_dtype)
or pa.types.is_decimal(pa_dtype)
):
mark = pytest.mark.xfail(
reason=(
f"GH#29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
f"for {pa_dtype}"
)
)
elif arrow_temporal_supported and (
pa.types.is_time(pa_dtype)
or (
opname
in ("__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__")
and pa.types.is_duration(pa_dtype)
)
):
mark = pytest.mark.xfail(
raises=TypeError,
reason=(
f"{opname} not supported between"
f"pd.NA and {pa_dtype} Python scalar"
),
)