-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathtest_table.py
More file actions
4193 lines (3360 loc) · 126 KB
/
Copy pathtest_table.py
File metadata and controls
4193 lines (3360 loc) · 126 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from collections import OrderedDict
from collections.abc import Iterable
import sys
import weakref
try:
import numpy as np
except ImportError:
np = None
import pytest
import pyarrow as pa
import pyarrow.compute as pc
from pyarrow.interchange import from_dataframe
from pyarrow.vendored.version import Version
def test_chunked_array_basics():
data = pa.chunked_array([], type=pa.string())
assert data.type == pa.string()
assert data.to_pylist() == []
data.validate()
data2 = pa.chunked_array([], type='binary')
assert data2.type == pa.binary()
with pytest.raises(ValueError):
pa.chunked_array([])
data = pa.chunked_array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
assert isinstance(data.chunks, list)
assert all(isinstance(c, pa.lib.Int64Array) for c in data.chunks)
assert all(isinstance(c, pa.lib.Int64Array) for c in data.iterchunks())
assert len(data.chunks) == 3
assert data.get_total_buffer_size() == sum(c.get_total_buffer_size()
for c in data.iterchunks())
assert sys.getsizeof(data) >= object.__sizeof__(
data) + data.get_total_buffer_size()
assert data.nbytes == 3 * 3 * 8 # 3 items per 3 lists with int64 size(8)
data.validate()
wr = weakref.ref(data)
assert wr() is not None
del data
assert wr() is None
def test_chunked_array_construction():
arr = pa.chunked_array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
assert arr.type == pa.int64()
assert len(arr) == 9
assert len(arr.chunks) == 3
arr = pa.chunked_array([
[1, 2, 3],
[4., 5., 6.],
[7, 8, 9],
])
assert arr.type == pa.int64()
assert len(arr) == 9
assert len(arr.chunks) == 3
arr = pa.chunked_array([
[1, 2, 3],
[4., 5., 6.],
[7, 8, 9],
], type=pa.int8())
assert arr.type == pa.int8()
assert len(arr) == 9
assert len(arr.chunks) == 3
arr = pa.chunked_array([
[1, 2, 3],
[]
])
assert arr.type == pa.int64()
assert len(arr) == 3
assert len(arr.chunks) == 2
msg = "cannot construct ChunkedArray from empty vector and omitted type"
with pytest.raises(ValueError, match=msg):
assert pa.chunked_array([])
assert pa.chunked_array([], type=pa.string()).type == pa.string()
assert pa.chunked_array([[]]).type == pa.null()
assert pa.chunked_array([[]], type=pa.string()).type == pa.string()
def test_combine_chunks():
# ARROW-77363
arr = pa.array([1, 2])
chunked_arr = pa.chunked_array([arr, arr])
res = chunked_arr.combine_chunks()
expected = pa.array([1, 2, 1, 2])
assert res.equals(expected)
def test_chunked_array_can_combine_chunks_with_no_chunks():
# https://issues.apache.org/jira/browse/ARROW-17256
assert pa.chunked_array([], type=pa.bool_()).combine_chunks() == pa.array(
[], type=pa.bool_()
)
assert pa.chunked_array(
[pa.array([], type=pa.bool_())], type=pa.bool_()
).combine_chunks() == pa.array([], type=pa.bool_())
@pytest.mark.numpy
def test_chunked_array_to_numpy():
data = pa.chunked_array([
[1, 2, 3],
[4, 5, 6],
[]
])
arr1 = np.asarray(data)
arr2 = data.to_numpy()
assert isinstance(arr2, np.ndarray)
assert arr2.shape == (6,)
assert np.array_equal(arr1, arr2)
def test_chunked_array_mismatch_types():
msg = "chunks must all be same type"
with pytest.raises(TypeError, match=msg):
# Given array types are different
pa.chunked_array([
pa.array([1, 2, 3]),
pa.array([1., 2., 3.])
])
with pytest.raises(TypeError, match=msg):
# Given array type is different from explicit type argument
pa.chunked_array([pa.array([1, 2, 3])], type=pa.float64())
def test_chunked_array_str():
data = [
pa.array([1, 2, 3]),
pa.array([4, 5, 6])
]
data = pa.chunked_array(data)
assert str(data) == """[
[
1,
2,
3
],
[
4,
5,
6
]
]"""
@pytest.mark.numpy
def test_chunked_array_getitem():
data = [
pa.array([1, 2, 3]),
pa.array([4, 5, 6])
]
data = pa.chunked_array(data)
assert data[1].as_py() == 2
assert data[-1].as_py() == 6
assert data[-6].as_py() == 1
with pytest.raises(IndexError):
data[6]
with pytest.raises(IndexError):
data[-7]
# Ensure this works with numpy scalars
assert data[np.int32(1)].as_py() == 2
data_slice = data[2:4]
assert data_slice.to_pylist() == [3, 4]
data_slice = data[4:-1]
assert data_slice.to_pylist() == [5]
data_slice = data[99:99]
assert data_slice.type == data.type
assert data_slice.to_pylist() == []
def test_chunked_array_slice():
data = [
pa.array([1, 2, 3]),
pa.array([4, 5, 6])
]
data = pa.chunked_array(data)
data_slice = data.slice(len(data))
assert data_slice.type == data.type
assert data_slice.to_pylist() == []
data_slice = data.slice(len(data) + 10)
assert data_slice.type == data.type
assert data_slice.to_pylist() == []
table = pa.Table.from_arrays([data], names=["a"])
table_slice = table.slice(len(table))
assert len(table_slice) == 0
table = pa.Table.from_arrays([data], names=["a"])
table_slice = table.slice(len(table) + 10)
assert len(table_slice) == 0
def test_chunked_array_iter():
data = [
pa.array([0]),
pa.array([1, 2, 3]),
pa.array([4, 5, 6]),
pa.array([7, 8, 9])
]
arr = pa.chunked_array(data)
for i, j in zip(range(10), arr):
assert i == j.as_py()
assert isinstance(arr, Iterable)
def test_chunked_array_equals():
def eq(xarrs, yarrs):
if isinstance(xarrs, pa.ChunkedArray):
x = xarrs
else:
x = pa.chunked_array(xarrs)
if isinstance(yarrs, pa.ChunkedArray):
y = yarrs
else:
y = pa.chunked_array(yarrs)
assert x.equals(y)
assert y.equals(x)
assert x == y
assert x != str(y)
def ne(xarrs, yarrs):
if isinstance(xarrs, pa.ChunkedArray):
x = xarrs
else:
x = pa.chunked_array(xarrs)
if isinstance(yarrs, pa.ChunkedArray):
y = yarrs
else:
y = pa.chunked_array(yarrs)
assert not x.equals(y)
assert not y.equals(x)
assert x != y
eq(pa.chunked_array([], type=pa.int32()),
pa.chunked_array([], type=pa.int32()))
ne(pa.chunked_array([], type=pa.int32()),
pa.chunked_array([], type=pa.int64()))
a = pa.array([0, 2], type=pa.int32())
b = pa.array([0, 2], type=pa.int64())
c = pa.array([0, 3], type=pa.int32())
d = pa.array([0, 2, 0, 3], type=pa.int32())
eq([a], [a])
ne([a], [b])
eq([a, c], [a, c])
eq([a, c], [d])
ne([c, a], [a, c])
# ARROW-4822
assert not pa.chunked_array([], type=pa.int32()).equals(None)
@pytest.mark.parametrize(
('data', 'typ'),
[
([True, False, True, True], pa.bool_()),
([1, 2, 4, 6], pa.int64()),
([1.0, 2.5, None], pa.float64()),
(['a', None, 'b'], pa.string()),
([], pa.list_(pa.uint8())),
([[1, 2], [3]], pa.list_(pa.int64())),
([['a'], None, ['b', 'c']], pa.list_(pa.string())),
([(1, 'a'), (2, 'c'), None],
pa.struct([pa.field('a', pa.int64()), pa.field('b', pa.string())]))
]
)
def test_chunked_array_pickle(data, typ, pickle_module):
arrays = []
while data:
arrays.append(pa.array(data[:2], type=typ))
data = data[2:]
array = pa.chunked_array(arrays, type=typ)
array.validate()
result = pickle_module.loads(pickle_module.dumps(array))
result.validate()
assert result.equals(array)
@pytest.mark.pandas
def test_chunked_array_to_pandas():
import pandas as pd
data = [
pa.array([-10, -5, 0, 5, 10])
]
table = pa.table(data, names=['a'])
col = table.column(0)
assert isinstance(col, pa.ChunkedArray)
series = col.to_pandas()
assert isinstance(series, pd.Series)
assert series.shape == (5,)
assert series[0] == -10
assert series.name == 'a'
@pytest.mark.pandas
def test_chunked_array_to_pandas_preserve_name():
# https://issues.apache.org/jira/browse/ARROW-7709
import pandas as pd
import pandas.testing as tm
for data in [
pa.array([1, 2, 3]),
pa.array(pd.Categorical(["a", "b", "a"])),
pa.array(pd.date_range("2012", periods=3)),
pa.array(pd.date_range("2012", periods=3, tz="Europe/Brussels")),
pa.array([1, 2, 3], pa.timestamp("ms")),
pa.array([1, 2, 3], pa.timestamp("ms", "Europe/Brussels"))]:
table = pa.table({"name": data})
result = table.column("name").to_pandas()
assert result.name == "name"
expected = pd.Series(data.to_pandas(), name="name")
tm.assert_series_equal(result, expected)
@pytest.mark.pandas
def test_table_roundtrip_to_pandas_empty_dataframe():
# https://issues.apache.org/jira/browse/ARROW-10643
# The conversion should not results in a table with 0 rows if the original
# DataFrame has a RangeIndex but is empty.
import pandas as pd
data = pd.DataFrame(index=pd.RangeIndex(0, 10, 1))
table = pa.table(data)
result = table.to_pandas()
assert table.num_rows == 10
assert data.shape == (10, 0)
assert result.shape == (10, 0)
assert result.index.equals(data.index)
data = pd.DataFrame(index=pd.RangeIndex(0, 10, 3))
table = pa.table(data)
result = table.to_pandas()
assert table.num_rows == 4
assert data.shape == (4, 0)
assert result.shape == (4, 0)
assert result.index.equals(data.index)
@pytest.mark.pandas
def test_recordbatch_roundtrip_to_pandas_empty_dataframe():
# https://issues.apache.org/jira/browse/ARROW-10643
# The conversion should not results in a RecordBatch with 0 rows if
# the original DataFrame has a RangeIndex but is empty.
import pandas as pd
data = pd.DataFrame(index=pd.RangeIndex(0, 10, 1))
batch = pa.RecordBatch.from_pandas(data)
result = batch.to_pandas()
assert batch.num_rows == 10
assert data.shape == (10, 0)
assert result.shape == (10, 0)
assert result.index.equals(data.index)
data = pd.DataFrame(index=pd.RangeIndex(0, 10, 3))
batch = pa.RecordBatch.from_pandas(data)
result = batch.to_pandas()
assert batch.num_rows == 4
assert data.shape == (4, 0)
assert result.shape == (4, 0)
assert result.index.equals(data.index)
@pytest.mark.pandas
def test_to_pandas_empty_table():
# https://issues.apache.org/jira/browse/ARROW-15370
import pandas as pd
import pandas.testing as tm
df = pd.DataFrame({'a': [1, 2], 'b': [0.1, 0.2]})
table = pa.table(df)
result = table.schema.empty_table().to_pandas()
assert result.shape == (0, 2)
tm.assert_frame_equal(result, df.iloc[:0])
@pytest.mark.pandas
@pytest.mark.nopandas
def test_chunked_array_asarray():
# ensure this is tested both when pandas is present or not (ARROW-6564)
data = [
pa.array([0]),
pa.array([1, 2, 3])
]
chunked_arr = pa.chunked_array(data)
np_arr = np.asarray(chunked_arr)
assert np_arr.tolist() == [0, 1, 2, 3]
assert np_arr.dtype == np.dtype('int64')
# An optional type can be specified when calling np.asarray
np_arr = np.asarray(chunked_arr, dtype='str')
assert np_arr.tolist() == ['0', '1', '2', '3']
# Types are modified when there are nulls
data = [
pa.array([1, None]),
pa.array([1, 2, 3])
]
chunked_arr = pa.chunked_array(data)
np_arr = np.asarray(chunked_arr)
elements = np_arr.tolist()
assert elements[0] == 1.
assert np.isnan(elements[1])
assert elements[2:] == [1., 2., 3.]
assert np_arr.dtype == np.dtype('float64')
# DictionaryType data will be converted to dense numpy array
arr = pa.DictionaryArray.from_arrays(
pa.array([0, 1, 2, 0, 1]), pa.array(['a', 'b', 'c']))
chunked_arr = pa.chunked_array([arr, arr])
np_arr = np.asarray(chunked_arr)
assert np_arr.dtype == np.dtype('object')
assert np_arr.tolist() == ['a', 'b', 'c', 'a', 'b'] * 2
def test_chunked_array_flatten():
ty = pa.struct([pa.field('x', pa.int16()),
pa.field('y', pa.float32())])
a = pa.array([(1, 2.5), (3, 4.5), (5, 6.5)], type=ty)
carr = pa.chunked_array(a)
x, y = carr.flatten()
assert x.equals(pa.chunked_array(pa.array([1, 3, 5], type=pa.int16())))
assert y.equals(pa.chunked_array(pa.array([2.5, 4.5, 6.5],
type=pa.float32())))
# Empty column
a = pa.array([], type=ty)
carr = pa.chunked_array(a)
x, y = carr.flatten()
assert x.equals(pa.chunked_array(pa.array([], type=pa.int16())))
assert y.equals(pa.chunked_array(pa.array([], type=pa.float32())))
def test_chunked_array_unify_dictionaries():
arr = pa.chunked_array([
pa.array(["foo", "bar", None, "foo"]).dictionary_encode(),
pa.array(["quux", None, "foo"]).dictionary_encode(),
])
assert arr.chunk(0).dictionary.equals(pa.array(["foo", "bar"]))
assert arr.chunk(1).dictionary.equals(pa.array(["quux", "foo"]))
arr = arr.unify_dictionaries()
expected_dict = pa.array(["foo", "bar", "quux"])
assert arr.chunk(0).dictionary.equals(expected_dict)
assert arr.chunk(1).dictionary.equals(expected_dict)
assert arr.to_pylist() == ["foo", "bar", None, "foo", "quux", None, "foo"]
def test_recordbatch_dunder_init():
with pytest.raises(TypeError, match='RecordBatch'):
pa.RecordBatch()
def test_chunked_array_c_array_interface():
class ArrayWrapper:
def __init__(self, array):
self.array = array
def __arrow_c_array__(self, requested_schema=None):
return self.array.__arrow_c_array__(requested_schema)
data = pa.array([1, 2, 3], pa.int64())
chunked = pa.chunked_array([data])
wrapper = ArrayWrapper(data)
# Can roundtrip through the wrapper.
result = pa.chunked_array(wrapper)
assert result == chunked
# Can also import with a type that implementer can cast to.
result = pa.chunked_array(wrapper, type=pa.int16())
assert result == chunked.cast(pa.int16())
def test_chunked_array_c_stream_interface():
class ChunkedArrayWrapper:
def __init__(self, chunked):
self.chunked = chunked
def __arrow_c_stream__(self, requested_schema=None):
return self.chunked.__arrow_c_stream__(requested_schema)
data = pa.chunked_array([[1, 2, 3], [4, None, 6]])
wrapper = ChunkedArrayWrapper(data)
# Can roundtrip through the wrapper.
result = pa.chunked_array(wrapper)
assert result == data
# Can also import with a type that implementer can cast to.
result = pa.chunked_array(wrapper, type=pa.int16())
assert result == data.cast(pa.int16())
class BatchWrapper:
def __init__(self, batch):
self.batch = batch
def __arrow_c_array__(self, requested_schema=None):
return self.batch.__arrow_c_array__(requested_schema)
class BatchDeviceWrapper:
def __init__(self, batch):
self.batch = batch
def __arrow_c_device_array__(self, requested_schema=None, **kwargs):
return self.batch.__arrow_c_device_array__(requested_schema, **kwargs)
@pytest.mark.parametrize("wrapper_class", [BatchWrapper, BatchDeviceWrapper])
def test_recordbatch_c_array_interface(wrapper_class):
data = pa.record_batch([
pa.array([1, 2, 3], type=pa.int64())
], names=['a'])
wrapper = wrapper_class(data)
# Can roundtrip through the wrapper.
result = pa.record_batch(wrapper)
assert result == data
# Can also import with a schema that implementer can cast to.
castable_schema = pa.schema([
pa.field('a', pa.int32())
])
result = pa.record_batch(wrapper, schema=castable_schema)
expected = pa.record_batch([
pa.array([1, 2, 3], type=pa.int32())
], names=['a'])
assert result == expected
def test_recordbatch_c_array_interface_device_unsupported_keyword():
# For the device-aware version, we raise a specific error for unsupported keywords
data = pa.record_batch(
[pa.array([1, 2, 3], type=pa.int64())], names=['a']
)
with pytest.raises(
NotImplementedError,
match=r"Received unsupported keyword argument\(s\): \['other'\]"
):
data.__arrow_c_device_array__(other="not-none")
# but with None value it is ignored
_ = data.__arrow_c_device_array__(other=None)
@pytest.mark.parametrize("wrapper_class", [BatchWrapper, BatchDeviceWrapper])
def test_table_c_array_interface(wrapper_class):
data = pa.record_batch([
pa.array([1, 2, 3], type=pa.int64())
], names=['a'])
wrapper = wrapper_class(data)
# Can roundtrip through the wrapper.
result = pa.table(wrapper)
expected = pa.Table.from_batches([data])
assert result == expected
# Can also import with a schema that implementer can cast to.
castable_schema = pa.schema([
pa.field('a', pa.int32())
])
result = pa.table(wrapper, schema=castable_schema)
expected = pa.table({
'a': pa.array([1, 2, 3], type=pa.int32())
})
assert result == expected
def test_table_c_stream_interface():
class StreamWrapper:
def __init__(self, batches):
self.batches = batches
def __arrow_c_stream__(self, requested_schema=None):
reader = pa.RecordBatchReader.from_batches(
self.batches[0].schema, self.batches)
return reader.__arrow_c_stream__(requested_schema)
data = [
pa.record_batch([pa.array([1, 2, 3], type=pa.int64())], names=['a']),
pa.record_batch([pa.array([4, 5, 6], type=pa.int64())], names=['a'])
]
wrapper = StreamWrapper(data)
# Can roundtrip through the wrapper.
result = pa.table(wrapper)
expected = pa.Table.from_batches(data)
assert result == expected
# Passing schema works if already that schema
result = pa.table(wrapper, schema=data[0].schema)
assert result == expected
# Passing a different schema will cast
good_schema = pa.schema([pa.field('a', pa.int32())])
result = pa.table(wrapper, schema=good_schema)
assert result == expected.cast(good_schema)
# If schema doesn't match, raises NotImplementedError
with pytest.raises(
pa.lib.ArrowTypeError, match="Field 0 cannot be cast"
):
pa.table(
wrapper, schema=pa.schema([pa.field('a', pa.list_(pa.int32()))])
)
def test_recordbatch_itercolumns():
data = [
pa.array(range(5), type='int16'),
pa.array([-10, -5, 0, None, 10], type='int32')
]
batch = pa.record_batch(data, ['c0', 'c1'])
columns = []
for col in batch.itercolumns():
columns.append(col)
assert batch.columns == columns
assert batch == pa.record_batch(columns, names=batch.column_names)
assert batch != pa.record_batch(columns[1:], names=batch.column_names[1:])
assert batch != columns
def test_recordbatch_equals():
data1 = [
pa.array(range(5), type='int16'),
pa.array([-10, -5, 0, None, 10], type='int32')
]
data2 = [
pa.array(['a', 'b', 'c']),
pa.array([['d'], ['e'], ['f']]),
]
column_names = ['c0', 'c1']
batch = pa.record_batch(data1, column_names)
assert batch == pa.record_batch(data1, column_names)
assert batch.equals(pa.record_batch(data1, column_names))
assert batch != pa.record_batch(data2, column_names)
assert not batch.equals(pa.record_batch(data2, column_names))
batch_meta = pa.record_batch(data1, names=column_names,
metadata={'key': 'value'})
assert batch_meta.equals(batch)
assert not batch_meta.equals(batch, check_metadata=True)
# ARROW-8889
assert not batch.equals(None)
assert batch != "foo"
def test_recordbatch_take():
batch = pa.record_batch(
[pa.array([1, 2, 3, None, 5]),
pa.array(['a', 'b', 'c', 'd', 'e'])],
['f1', 'f2'])
assert batch.take(pa.array([2, 3])).equals(batch.slice(2, 2))
assert batch.take(pa.array([2, None])).equals(
pa.record_batch([pa.array([3, None]), pa.array(['c', None])],
['f1', 'f2']))
def test_recordbatch_column_sets_private_name():
# ARROW-6429
rb = pa.record_batch([pa.array([1, 2, 3, 4])], names=['a0'])
assert rb[0]._name == 'a0'
def test_recordbatch_from_arrays_validate_schema():
# ARROW-6263
arr = pa.array([1, 2])
schema = pa.schema([pa.field('f0', pa.list_(pa.utf8()))])
with pytest.raises(NotImplementedError):
pa.record_batch([arr], schema=schema)
def test_recordbatch_from_arrays_validate_lengths():
# ARROW-2820
data = [pa.array([1]), pa.array(["tokyo", "like", "happy"]),
pa.array(["derek"])]
with pytest.raises(ValueError):
pa.record_batch(data, ['id', 'tags', 'name'])
def test_recordbatch_no_fields():
batch = pa.record_batch([], [])
assert len(batch) == 0
assert batch.num_rows == 0
assert batch.num_columns == 0
def test_recordbatch_from_arrays_invalid_names():
data = [
pa.array(range(5)),
pa.array([-10, -5, 0, 5, 10])
]
with pytest.raises(ValueError):
pa.record_batch(data, names=['a', 'b', 'c'])
with pytest.raises(ValueError):
pa.record_batch(data, names=['a'])
def test_recordbatch_empty_metadata():
data = [
pa.array(range(5)),
pa.array([-10, -5, 0, 5, 10])
]
batch = pa.record_batch(data, ['c0', 'c1'])
assert batch.schema.metadata is None
def test_recordbatch_pickle(pickle_module):
data = [
pa.array(range(5), type='int8'),
pa.array([-10, -5, 0, 5, 10], type='float32')
]
fields = [
pa.field('ints', pa.int8()),
pa.field('floats', pa.float32()),
]
schema = pa.schema(fields, metadata={b'foo': b'bar'})
batch = pa.record_batch(data, schema=schema)
result = pickle_module.loads(pickle_module.dumps(batch))
assert result.equals(batch)
assert result.schema == schema
def test_recordbatch_get_field():
data = [
pa.array(range(5)),
pa.array([-10, -5, 0, 5, 10]),
pa.array(range(5, 10))
]
batch = pa.RecordBatch.from_arrays(data, names=('a', 'b', 'c'))
assert batch.field('a').equals(batch.schema.field('a'))
assert batch.field(0).equals(batch.schema.field('a'))
with pytest.raises(KeyError):
batch.field('d')
with pytest.raises(TypeError):
batch.field(None)
with pytest.raises(IndexError):
batch.field(4)
def test_recordbatch_select_column():
data = [
pa.array(range(5)),
pa.array([-10, -5, 0, 5, 10]),
pa.array(range(5, 10))
]
batch = pa.RecordBatch.from_arrays(data, names=('a', 'b', 'c'))
assert batch.column('a').equals(batch.column(0))
with pytest.raises(
KeyError, match='Field "d" does not exist in schema'):
batch.column('d')
with pytest.raises(TypeError):
batch.column(None)
with pytest.raises(IndexError):
batch.column(4)
def test_recordbatch_select():
a1 = pa.array([1, 2, 3, None, 5])
a2 = pa.array(['a', 'b', 'c', 'd', 'e'])
a3 = pa.array([[1, 2], [3, 4], [5, 6], None, [9, 10]])
batch = pa.record_batch([a1, a2, a3], ['f1', 'f2', 'f3'])
# selecting with string names
result = batch.select(['f1'])
expected = pa.record_batch([a1], ['f1'])
assert result.equals(expected)
result = batch.select(['f3', 'f2'])
expected = pa.record_batch([a3, a2], ['f3', 'f2'])
assert result.equals(expected)
# selecting with integer indices
result = batch.select([0])
expected = pa.record_batch([a1], ['f1'])
assert result.equals(expected)
result = batch.select([2, 1])
expected = pa.record_batch([a3, a2], ['f3', 'f2'])
assert result.equals(expected)
# preserve metadata
batch2 = batch.replace_schema_metadata({"a": "test"})
result = batch2.select(["f1", "f2"])
assert b"a" in result.schema.metadata
# selecting non-existing column raises
with pytest.raises(KeyError, match='Field "f5" does not exist'):
batch.select(['f5'])
with pytest.raises(IndexError, match="index out of bounds"):
batch.select([5])
# duplicate selection gives duplicated names in resulting recordbatch
result = batch.select(['f2', 'f2'])
expected = pa.record_batch([a2, a2], ['f2', 'f2'])
assert result.equals(expected)
# selection duplicated column raises
batch = pa.record_batch([a1, a2, a3], ['f1', 'f2', 'f1'])
with pytest.raises(KeyError, match='Field "f1" exists 2 times'):
batch.select(['f1'])
result = batch.select(['f2'])
expected = pa.record_batch([a2], ['f2'])
assert result.equals(expected)
def test_recordbatch_from_struct_array_invalid():
with pytest.raises(TypeError):
pa.RecordBatch.from_struct_array(pa.array(range(5)))
def test_recordbatch_from_struct_array():
struct_array = pa.array(
[{"ints": 1}, {"floats": 1.0}],
type=pa.struct([("ints", pa.int32()), ("floats", pa.float32())]),
)
result = pa.RecordBatch.from_struct_array(struct_array)
assert result.equals(pa.RecordBatch.from_arrays(
[
pa.array([1, None], type=pa.int32()),
pa.array([None, 1.0], type=pa.float32()),
], ["ints", "floats"]
))
def test_recordbatch_to_struct_array():
batch = pa.RecordBatch.from_arrays(
[
pa.array([1, None], type=pa.int32()),
pa.array([None, 1.0], type=pa.float32()),
], ["ints", "floats"]
)
result = batch.to_struct_array()
assert result.equals(pa.array(
[{"ints": 1}, {"floats": 1.0}],
type=pa.struct([("ints", pa.int32()), ("floats", pa.float32())]),
))
def test_table_from_struct_array_invalid():
with pytest.raises(TypeError, match="Argument 'struct_array' has incorrect type"):
pa.Table.from_struct_array(pa.array(range(5)))
def test_table_from_struct_array():
struct_array = pa.array(
[{"ints": 1}, {"floats": 1.0}],
type=pa.struct([("ints", pa.int32()), ("floats", pa.float32())]),
)
result = pa.Table.from_struct_array(struct_array)
assert result.equals(pa.Table.from_arrays(
[
pa.array([1, None], type=pa.int32()),
pa.array([None, 1.0], type=pa.float32()),
], ["ints", "floats"]
))
def test_table_from_struct_array_chunked_array():
chunked_struct_array = pa.chunked_array(
[[{"ints": 1}, {"floats": 1.0}]],
type=pa.struct([("ints", pa.int32()), ("floats", pa.float32())]),
)
result = pa.Table.from_struct_array(chunked_struct_array)
assert result.equals(pa.Table.from_arrays(
[
pa.array([1, None], type=pa.int32()),
pa.array([None, 1.0], type=pa.float32()),
], ["ints", "floats"]
))
def test_table_to_struct_array():
table = pa.Table.from_arrays(
[
pa.array([1, None], type=pa.int32()),
pa.array([None, 1.0], type=pa.float32()),
], ["ints", "floats"]
)
result = table.to_struct_array()
assert result.equals(pa.chunked_array(
[[{"ints": 1}, {"floats": 1.0}]],
type=pa.struct([("ints", pa.int32()), ("floats", pa.float32())]),
))
def test_table_to_struct_array_with_max_chunksize():
table = pa.Table.from_arrays(
[
pa.array([1, None], type=pa.int32()),
pa.array([None, 1.0], type=pa.float32()),
], ["ints", "floats"]
)
result = table.to_struct_array(max_chunksize=1)
assert result.equals(pa.chunked_array(
[[{"ints": 1}], [{"floats": 1.0}]],
type=pa.struct([("ints", pa.int32()), ("floats", pa.float32())]),
))
def test_table_to_struct_array_for_empty_table():
table = pa.Table.from_arrays(
[
pa.array([], type=pa.int32()),
pa.array([], type=pa.float32()),
], ["ints", "floats"]
)
result = table.to_struct_array()
assert result.equals(
pa.chunked_array(
[],
type=pa.struct({"ints": pa.int32(), "floats": pa.float32()}),
),
)
def check_tensors(tensor, expected_tensor, type, size):
assert tensor.equals(expected_tensor)
assert tensor.size == size
assert tensor.type == type
assert tensor.shape == expected_tensor.shape
assert tensor.strides == expected_tensor.strides
@pytest.mark.numpy
@pytest.mark.parametrize('typ_str', [
"uint8", "uint16", "uint32", "uint64",
"int8", "int16", "int32", "int64",