forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_arrow.py
2599 lines (2224 loc) · 87.8 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 datetime import (
date,
datetime,
time,
timedelta,
)
from decimal import Decimal
from io import (
BytesIO,
StringIO,
)
import operator
import pickle
import re
import numpy as np
import pytest
from pandas._libs import lib
from pandas.compat import (
PY311,
is_ci_environment,
is_platform_windows,
pa_version_under7p0,
pa_version_under8p0,
pa_version_under9p0,
pa_version_under11p0,
)
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.dtypes import CategoricalDtypeType
import pandas as pd
import pandas._testing as tm
from pandas.api.types import (
is_bool_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", minversion="7.0.0")
from pandas.core.arrays.arrow.array import ArrowExtensionArray
from pandas.core.arrays.arrow.dtype import ArrowDtype # isort:skip
@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]])
@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]]
)
@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]]
)
@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):
return pd.array([2] * 100, dtype=data.dtype)
# tests will be xfailed where 2 is not a valid scalar for pa_dtype
return data
@pytest.fixture
def na_value():
"""The scalar missing value for this type. Default 'None'"""
return pd.NA
class TestBaseCasting(base.BaseCastingTests):
def test_astype_str(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_binary(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
reason=f"For {pa_dtype} .astype(str) decodes.",
)
)
super().test_astype_str(data)
class TestConstructors(base.BaseConstructorsTests):
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.node.add_marker(
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)
tm.assert_extension_array_equal(result, data)
assert isinstance(result._pa_array, pa.ChunkedArray)
result = type(data)._from_sequence(data._pa_array.combine_chunks())
tm.assert_extension_array_equal(result, data)
assert isinstance(result._pa_array, pa.ChunkedArray)
def test_from_sequence_pa_array_notimplemented(self, request):
with pytest.raises(NotImplementedError, match="Converting strings to"):
ArrowExtensionArray._from_sequence_of_strings(
["12-1"], dtype=pa.month_day_nano_interval()
)
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.node.add_marker(
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.node.add_marker(
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:
if is_platform_windows() and is_ci_environment():
request.node.add_marker(
pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason=(
"TODO: Set ARROW_TIMEZONE_DATABASE environment variable "
"on CI to path to the tzdata for pyarrow."
),
)
)
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)
class TestGetitemTests(base.BaseGetitemTests):
pass
class TestBaseAccumulateTests(base.BaseAccumulateTests):
def check_accumulate(self, ser, op_name, skipna):
result = getattr(ser, op_name)(skipna=skipna)
if ser.dtype.kind == "m":
# Just check that we match the integer behavior.
ser = ser.astype("int64[pyarrow]")
result = result.astype("int64[pyarrow]")
result = result.astype("Float64")
expected = getattr(ser.astype("Float64"), op_name)(skipna=skipna)
self.assert_series_equal(result, expected, check_dtype=False)
@pytest.mark.parametrize("skipna", [True, False])
def test_accumulate_series_raises(self, data, all_numeric_accumulations, skipna):
pa_type = data.dtype.pyarrow_dtype
if (
(
pa.types.is_integer(pa_type)
or pa.types.is_floating(pa_type)
or pa.types.is_duration(pa_type)
)
and all_numeric_accumulations == "cumsum"
and not pa_version_under9p0
):
pytest.skip("These work, are tested by test_accumulate_series.")
op_name = all_numeric_accumulations
ser = pd.Series(data)
with pytest.raises(NotImplementedError):
getattr(ser, op_name)(skipna=skipna)
@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)
do_skip = False
if pa.types.is_string(pa_type) or pa.types.is_binary(pa_type):
if op_name in ["cumsum", "cumprod"]:
do_skip = True
elif pa.types.is_temporal(pa_type) and not pa.types.is_duration(pa_type):
if op_name in ["cumsum", "cumprod"]:
do_skip = True
elif pa.types.is_duration(pa_type):
if op_name == "cumprod":
do_skip = True
if do_skip:
pytest.skip(
f"{op_name} should *not* work, we test in "
"test_accumulate_series_raises that these correctly raise."
)
if all_numeric_accumulations != "cumsum" or pa_version_under9p0:
# 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.node.add_marker(mark)
elif all_numeric_accumulations == "cumsum" and (
pa.types.is_boolean(pa_type) or pa.types.is_decimal(pa_type)
):
request.node.add_marker(
pytest.mark.xfail(
reason=f"{all_numeric_accumulations} not implemented for {pa_type}",
raises=NotImplementedError,
)
)
self.check_accumulate(ser, op_name, skipna)
class TestBaseNumericReduce(base.BaseNumericReduceTests):
def check_reduce(self, ser, op_name, skipna):
pa_dtype = ser.dtype.pyarrow_dtype
if op_name == "count":
result = getattr(ser, op_name)()
else:
result = getattr(ser, op_name)(skipna=skipna)
if pa.types.is_boolean(pa_dtype):
# Can't convert if ser contains NA
pytest.skip(
"pandas boolean data with NA does not fully support all reductions"
)
elif pa.types.is_integer(pa_dtype) or pa.types.is_floating(pa_dtype):
ser = ser.astype("Float64")
if op_name == "count":
expected = getattr(ser, op_name)()
else:
expected = getattr(ser, op_name)(skipna=skipna)
tm.assert_almost_equal(result, expected)
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series(self, data, all_numeric_reductions, skipna, request):
pa_dtype = data.dtype.pyarrow_dtype
opname = all_numeric_reductions
ser = pd.Series(data)
should_work = True
if pa.types.is_temporal(pa_dtype) and opname in [
"sum",
"var",
"skew",
"kurt",
"prod",
]:
if pa.types.is_duration(pa_dtype) and opname in ["sum"]:
# summing timedeltas is one case that *is* well-defined
pass
else:
should_work = False
elif (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
) and opname in [
"sum",
"mean",
"median",
"prod",
"std",
"sem",
"var",
"skew",
"kurt",
]:
should_work = False
if not should_work:
# matching the non-pyarrow versions, these operations *should* not
# work for these dtypes
msg = f"does not support reduction '{opname}'"
with pytest.raises(TypeError, match=msg):
getattr(ser, opname)(skipna=skipna)
return
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"}:
request.node.add_marker(xfail_mark)
elif (
all_numeric_reductions in {"var", "std", "median"}
and pa_version_under7p0
and pa.types.is_decimal(pa_dtype)
):
request.node.add_marker(xfail_mark)
elif all_numeric_reductions == "sem" and pa_version_under8p0:
request.node.add_marker(xfail_mark)
elif pa.types.is_boolean(pa_dtype) and all_numeric_reductions in {
"sem",
"std",
"var",
"median",
}:
request.node.add_marker(xfail_mark)
super().test_reduce_series(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
class TestBaseBooleanReduce(base.BaseBooleanReduceTests):
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series(
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.node.add_marker(xfail_mark)
op_name = all_boolean_reductions
ser = pd.Series(data)
if pa.types.is_temporal(pa_dtype) and not pa.types.is_duration(pa_dtype):
# 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.
with pytest.raises(TypeError, match="does not support reduction"):
getattr(ser, op_name)(skipna=skipna)
return
result = getattr(ser, op_name)(skipna=skipna)
assert result is (op_name == "any")
class TestBaseGroupby(base.BaseGroupbyTests):
def test_groupby_extension_no_sort(self, data_for_grouping, request):
pa_dtype = data_for_grouping.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
reason=f"{pa_dtype} only has 2 unique possible values",
)
)
super().test_groupby_extension_no_sort(data_for_grouping)
def test_groupby_extension_transform(self, data_for_grouping, request):
pa_dtype = data_for_grouping.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
reason=f"{pa_dtype} only has 2 unique possible values",
)
)
super().test_groupby_extension_transform(data_for_grouping)
@pytest.mark.parametrize("as_index", [True, False])
def test_groupby_extension_agg(self, as_index, data_for_grouping, request):
pa_dtype = data_for_grouping.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
raises=ValueError,
reason=f"{pa_dtype} only has 2 unique possible values",
)
)
super().test_groupby_extension_agg(as_index, data_for_grouping)
def test_in_numeric_groupby(self, data_for_grouping):
if is_string_dtype(data_for_grouping.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"])
with pytest.raises(TypeError, match="does not support"):
df.groupby("A").sum().columns
result = df.groupby("A").sum(numeric_only=True).columns
tm.assert_index_equal(result, expected)
else:
super().test_in_numeric_groupby(data_for_grouping)
class TestBaseDtype(base.BaseDtypeTests):
def test_construct_from_string_own_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_decimal(pa_dtype):
request.node.add_marker(
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.node.add_marker(
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.node.add_marker(
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)
class TestBaseIndex(base.BaseIndexTests):
pass
class TestBaseInterface(base.BaseInterfaceTests):
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views.", run=False
)
def test_view(self, data):
super().test_view(data)
class TestBaseMissing(base.BaseMissingTests):
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
self.assert_extension_array_equal(result, data)
result = data.fillna(method="backfill")
assert result is not data
self.assert_extension_array_equal(result, data)
def test_fillna_series_method(self, data_missing, fillna_method):
with tm.maybe_produces_warning(
PerformanceWarning, fillna_method is not None, check_stacklevel=False
):
super().test_fillna_series_method(data_missing, fillna_method)
class TestBasePrinting(base.BasePrintingTests):
pass
class TestBaseReshaping(base.BaseReshapingTests):
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
)
def test_transpose(self, data):
super().test_transpose(data)
class TestBaseSetitem(base.BaseSetitemTests):
@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)
class TestBaseParsing(base.BaseParsingTests):
@pytest.mark.parametrize("engine", ["c", "python"])
def test_EA_types(self, engine, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(raises=TypeError, reason="GH 47534")
)
elif pa.types.is_decimal(pa_dtype):
request.node.add_marker(
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.node.add_marker(
pytest.mark.xfail(
raises=ValueError,
reason="https://github.com/pandas-dev/pandas/issues/49767",
)
)
elif pa.types.is_binary(pa_dtype):
request.node.add_marker(
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
)
expected = df
self.assert_frame_equal(result, expected)
class TestBaseUnaryOps(base.BaseUnaryOpsTests):
def test_invert(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if not pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
raises=pa.ArrowNotImplementedError,
reason=f"pyarrow.compute.invert does support {pa_dtype}",
)
)
super().test_invert(data)
class TestBaseMethods(base.BaseMethodsTests):
@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.node.add_marker(
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())
def test_value_counts_with_normalize(self, data, request):
data = data[:10].unique()
values = np.array(data[~data.isna()])
ser = pd.Series(data, dtype=data.dtype)
result = ser.value_counts(normalize=True).sort_index()
expected = pd.Series(
[1 / len(values)] * len(values), index=result.index, name="proportion"
)
expected = expected.astype("double[pyarrow]")
self.assert_series_equal(result, expected)
def test_argmin_argmax(
self, data_for_sorting, data_missing_for_sorting, na_value, request
):
pa_dtype = data_for_sorting.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
reason=f"{pa_dtype} only has 2 unique possible values",
)
)
elif pa.types.is_decimal(pa_dtype) and pa_version_under7p0:
request.node.add_marker(
pytest.mark.xfail(
reason=f"No pyarrow kernel for {pa_dtype}",
raises=pa.ArrowNotImplementedError,
)
)
super().test_argmin_argmax(data_for_sorting, data_missing_for_sorting, na_value)
@pytest.mark.parametrize(
"op_name, skipna, expected",
[
("idxmax", True, 0),
("idxmin", True, 2),
("argmax", True, 0),
("argmin", True, 2),
("idxmax", False, np.nan),
("idxmin", False, np.nan),
("argmax", False, -1),
("argmin", False, -1),
],
)
def test_argreduce_series(
self, data_missing_for_sorting, op_name, skipna, expected, request
):
pa_dtype = data_missing_for_sorting.dtype.pyarrow_dtype
if pa.types.is_decimal(pa_dtype) and pa_version_under7p0 and skipna:
request.node.add_marker(
pytest.mark.xfail(
reason=f"No pyarrow kernel for {pa_dtype}",
raises=pa.ArrowNotImplementedError,
)
)
super().test_argreduce_series(
data_missing_for_sorting, op_name, skipna, expected
)
def test_factorize(self, data_for_grouping, request):
pa_dtype = data_for_grouping.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
reason=f"{pa_dtype} only has 2 unique possible values",
)
)
super().test_factorize(data_for_grouping)
_combine_le_expected_dtype = "bool[pyarrow]"
def test_combine_add(self, data_repeated, request):
pa_dtype = next(data_repeated(1)).dtype.pyarrow_dtype
if pa.types.is_temporal(pa_dtype) and not pa.types.is_duration(pa_dtype):
# analogous to datetime64, these cannot be added
orig_data1, orig_data2 = data_repeated(2)
s1 = pd.Series(orig_data1)
s2 = pd.Series(orig_data2)
with pytest.raises(TypeError):
s1.combine(s2, lambda x1, x2: x1 + x2)
else:
super().test_combine_add(data_repeated)
def test_searchsorted(self, data_for_sorting, as_series, request):
pa_dtype = data_for_sorting.dtype.pyarrow_dtype
if pa.types.is_boolean(pa_dtype):
request.node.add_marker(
pytest.mark.xfail(
reason=f"{pa_dtype} only has 2 unique possible values",
)
)
super().test_searchsorted(data_for_sorting, as_series)
def test_basic_equals(self, data):
# https://github.com/pandas-dev/pandas/issues/34660
assert pd.Series(data).equals(pd.Series(data))
class TestBaseArithmeticOps(base.BaseArithmeticOpsTests):
divmod_exc = NotImplementedError
@classmethod
def assert_equal(cls, left, right, **kwargs):
if isinstance(left, pd.DataFrame):
left_pa_type = left.iloc[:, 0].dtype.pyarrow_dtype
right_pa_type = right.iloc[:, 0].dtype.pyarrow_dtype
else:
left_pa_type = left.dtype.pyarrow_dtype
right_pa_type = right.dtype.pyarrow_dtype
if pa.types.is_decimal(left_pa_type) or pa.types.is_decimal(right_pa_type):
# decimal precision can resize in the result type depending on data
# just compare the float values
left = left.astype("float[pyarrow]")
right = right.astype("float[pyarrow]")
tm.assert_equal(left, right, **kwargs)
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
return lambda x, y: np.divide(y, x)
elif short_opname == "rfloordiv":
return lambda x, y: np.floor_divide(y, x)
return tm.get_op_from_name(op_name)
def _patch_combine(self, obj, other, op):
# BaseOpsUtil._combine can upcast expected dtype
# (because it generates expected on python scalars)
# while ArrowExtensionArray maintains original type
expected = base.BaseArithmeticOpsTests._combine(self, obj, other, op)
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
pa_expected = pa.array(expected_data._values)
if pa.types.is_duration(pa_expected.type):
orig_pa_type = original_dtype.pyarrow_dtype
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}]")
else:
pa_expected = pa_expected.cast(original_dtype.pyarrow_dtype)
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 not pa_version_under8p0 and (
opname in ("__add__", "__radd__")
and pa.types.is_duration(pa_dtype)
or opname in ("__sub__", "__rsub__")
and pa.types.is_temporal(pa_dtype)
)
def _get_scalar_exception(self, opname, pa_dtype):
arrow_temporal_supported = self._is_temporal_supported(opname, pa_dtype)
if opname in {
"__mod__",
"__rmod__",
}:
exc = NotImplementedError
elif arrow_temporal_supported:
exc = None
elif opname 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)
):
exc = pa.ArrowNotImplementedError
else:
exc = None