Repository navigation
Expand file tree
/
Copy patharrow_to_pandas.cc
More file actions
2071 lines (1775 loc) · 70.9 KB
/
Copy patharrow_to_pandas.cc
File metadata and controls
2071 lines (1775 loc) · 70.9 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.
// Functions for pandas conversion via NumPy
#include "arrow/python/numpy_interop.h" // IWYU pragma: expand
#include "arrow/python/arrow_to_pandas.h"
#include <cmath>
#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/status.h"
#include "arrow/table.h"
#include "arrow/type.h"
#include "arrow/type_traits.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/hashing.h"
#include "arrow/util/logging.h"
#include "arrow/util/macros.h"
#include "arrow/util/parallel.h"
#include "arrow/util/string_view.h"
#include "arrow/visitor_inline.h"
#include "arrow/compute/api.h"
#include "arrow/python/common.h"
#include "arrow/python/config.h"
#include "arrow/python/datetime.h"
#include "arrow/python/decimal.h"
#include "arrow/python/helpers.h"
#include "arrow/python/numpy_convert.h"
#include "arrow/python/numpy_internal.h"
#include "arrow/python/python_to_arrow.h"
#include "arrow/python/type_traits.h"
namespace arrow {
class MemoryPool;
using internal::checked_cast;
using internal::ParallelFor;
namespace py {
using internal::kNanosecondsInDay;
using internal::kPandasTimestampNull;
using compute::Datum;
using compute::FunctionContext;
// ----------------------------------------------------------------------
// Utility code
template <typename T>
struct WrapBytes {};
template <>
struct WrapBytes<StringType> {
static inline PyObject* Wrap(const char* data, int64_t length) {
return PyUnicode_FromStringAndSize(data, length);
}
};
template <>
struct WrapBytes<LargeStringType> {
static inline PyObject* Wrap(const char* data, int64_t length) {
return PyUnicode_FromStringAndSize(data, length);
}
};
template <>
struct WrapBytes<BinaryType> {
static inline PyObject* Wrap(const char* data, int64_t length) {
return PyBytes_FromStringAndSize(data, length);
}
};
template <>
struct WrapBytes<LargeBinaryType> {
static inline PyObject* Wrap(const char* data, int64_t length) {
return PyBytes_FromStringAndSize(data, length);
}
};
template <>
struct WrapBytes<FixedSizeBinaryType> {
static inline PyObject* Wrap(const char* data, int64_t length) {
return PyBytes_FromStringAndSize(data, length);
}
};
static inline bool ListTypeSupported(const DataType& type) {
switch (type.id()) {
case Type::BOOL:
case Type::UINT8:
case Type::INT8:
case Type::UINT16:
case Type::INT16:
case Type::UINT32:
case Type::INT32:
case Type::INT64:
case Type::UINT64:
case Type::FLOAT:
case Type::DOUBLE:
case Type::DECIMAL:
case Type::BINARY:
case Type::STRING:
case Type::DATE32:
case Type::DATE64:
case Type::TIME32:
case Type::TIME64:
case Type::TIMESTAMP:
case Type::NA: // empty list
// The above types are all supported.
return true;
case Type::LIST: {
const ListType& list_type = checked_cast<const ListType&>(type);
return ListTypeSupported(*list_type.value_type());
}
default:
break;
}
return false;
}
// ----------------------------------------------------------------------
// PyCapsule code for setting ndarray base to reference C++ object
struct ArrayCapsule {
std::shared_ptr<Array> array;
};
struct BufferCapsule {
std::shared_ptr<Buffer> buffer;
};
namespace {
void ArrayCapsule_Destructor(PyObject* capsule) {
delete reinterpret_cast<ArrayCapsule*>(PyCapsule_GetPointer(capsule, "arrow::Array"));
}
void BufferCapsule_Destructor(PyObject* capsule) {
delete reinterpret_cast<BufferCapsule*>(PyCapsule_GetPointer(capsule, "arrow::Buffer"));
}
} // namespace
Status CapsulizeArray(const std::shared_ptr<Array>& arr, PyObject** out) {
auto capsule = new ArrayCapsule{{arr}};
*out = PyCapsule_New(reinterpret_cast<void*>(capsule), "arrow::Array",
&ArrayCapsule_Destructor);
if (*out == nullptr) {
delete capsule;
RETURN_IF_PYERROR();
}
return Status::OK();
}
Status CapsulizeBuffer(const std::shared_ptr<Buffer>& buffer, PyObject** out) {
auto capsule = new BufferCapsule{{buffer}};
*out = PyCapsule_New(reinterpret_cast<void*>(capsule), "arrow::Buffer",
&BufferCapsule_Destructor);
if (*out == nullptr) {
delete capsule;
RETURN_IF_PYERROR();
}
return Status::OK();
}
Status SetNdarrayBase(PyArrayObject* arr, PyObject* base) {
if (PyArray_SetBaseObject(arr, base) == -1) {
// Error occurred, trust that SetBaseObject sets the error state
Py_XDECREF(base);
RETURN_IF_PYERROR();
}
return Status::OK();
}
Status SetBufferBase(PyArrayObject* arr, const std::shared_ptr<Buffer>& buffer) {
PyObject* base;
RETURN_NOT_OK(CapsulizeBuffer(buffer, &base));
return SetNdarrayBase(arr, base);
}
// ----------------------------------------------------------------------
// pandas 0.x DataFrame conversion internals
inline void set_numpy_metadata(int type, const DataType* datatype, PyArray_Descr* out) {
if (type == NPY_DATETIME) {
auto date_dtype = reinterpret_cast<PyArray_DatetimeDTypeMetaData*>(out->c_metadata);
if (datatype->id() == Type::TIMESTAMP) {
const auto& timestamp_type = checked_cast<const TimestampType&>(*datatype);
switch (timestamp_type.unit()) {
case TimestampType::Unit::SECOND:
date_dtype->meta.base = NPY_FR_s;
break;
case TimestampType::Unit::MILLI:
date_dtype->meta.base = NPY_FR_ms;
break;
case TimestampType::Unit::MICRO:
date_dtype->meta.base = NPY_FR_us;
break;
case TimestampType::Unit::NANO:
date_dtype->meta.base = NPY_FR_ns;
break;
}
} else {
// datatype->type == Type::DATE64
date_dtype->meta.base = NPY_FR_D;
}
}
}
namespace {
Status PyArray_NewFromPool(int nd, npy_intp* dims, int typenum,
const DataType* arrow_type, MemoryPool* pool, PyObject** out) {
// ARROW-6570: Allocate memory from MemoryPool for a couple reasons
//
// * Track allocations
// * Get better performance through custom allocators
PyArray_Descr* descr = internal::GetSafeNumPyDtype(typenum);
if (arrow_type != nullptr) {
set_numpy_metadata(typenum, arrow_type, descr);
}
int64_t total_size = descr->elsize;
for (int i = 0; i < nd; ++i) {
total_size *= dims[i];
}
std::shared_ptr<Buffer> buffer;
RETURN_NOT_OK(AllocateBuffer(pool, total_size, &buffer));
*out = PyArray_NewFromDescr(&PyArray_Type, descr, nd, dims,
/*strides=*/nullptr,
/*data=*/buffer->mutable_data(),
/*flags=*/NPY_ARRAY_CARRAY | NPY_ARRAY_WRITEABLE,
/*obj=*/nullptr);
if (*out == nullptr) {
RETURN_IF_PYERROR();
// Trust that error set if NULL returned
}
return SetBufferBase(reinterpret_cast<PyArrayObject*>(*out), buffer);
}
} // namespace
class PandasBlock {
public:
enum type {
OBJECT,
UINT8,
INT8,
UINT16,
INT16,
UINT32,
INT32,
UINT64,
INT64,
HALF_FLOAT,
FLOAT,
DOUBLE,
BOOL,
DATETIME,
DATETIME_WITH_TZ,
CATEGORICAL
};
PandasBlock(const PandasOptions& options, int64_t num_rows, int num_columns)
: num_rows_(num_rows), num_columns_(num_columns), options_(options) {}
virtual ~PandasBlock() {}
virtual Status Allocate() = 0;
virtual Status Write(std::shared_ptr<ChunkedArray> data, int64_t abs_placement,
int64_t rel_placement) = 0;
PyObject* block_arr() const { return block_arr_.obj(); }
virtual Status GetPyResult(PyObject** output) {
PyObject* result = PyDict_New();
RETURN_IF_PYERROR();
PyDict_SetItemString(result, "block", block_arr_.obj());
PyDict_SetItemString(result, "placement", placement_arr_.obj());
*output = result;
return Status::OK();
}
protected:
Status AllocateNDArray(int npy_type, int ndim = 2) {
PyAcquireGIL lock;
PyObject* block_arr;
npy_intp block_dims[2] = {0, 0};
if (ndim == 2) {
block_dims[0] = num_columns_;
block_dims[1] = num_rows_;
} else {
block_dims[0] = num_rows_;
}
RETURN_NOT_OK(PyArray_NewFromPool(ndim, block_dims, npy_type,
/*arrow_type=*/nullptr, options_.pool, &block_arr));
npy_intp placement_dims[1] = {num_columns_};
PyObject* placement_arr = PyArray_SimpleNew(1, placement_dims, NPY_INT64);
RETURN_IF_PYERROR();
block_arr_.reset(block_arr);
placement_arr_.reset(placement_arr);
block_data_ = reinterpret_cast<uint8_t*>(
PyArray_DATA(reinterpret_cast<PyArrayObject*>(block_arr)));
placement_data_ = reinterpret_cast<int64_t*>(
PyArray_DATA(reinterpret_cast<PyArrayObject*>(placement_arr)));
return Status::OK();
}
int64_t num_rows_;
int num_columns_;
OwnedRefNoGIL block_arr_;
uint8_t* block_data_;
PandasOptions options_;
// ndarray<int32>
OwnedRefNoGIL placement_arr_;
int64_t* placement_data_;
private:
ARROW_DISALLOW_COPY_AND_ASSIGN(PandasBlock);
};
template <typename T>
inline const T* GetPrimitiveValues(const Array& arr) {
if (arr.length() == 0) {
return nullptr;
}
const auto& prim_arr = checked_cast<const PrimitiveArray&>(arr);
const T* raw_values = reinterpret_cast<const T*>(prim_arr.values()->data());
return raw_values + arr.offset();
}
template <typename T>
inline void ConvertIntegerWithNulls(const PandasOptions& options,
const ChunkedArray& data, double* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = *data.chunk(c);
const T* in_values = GetPrimitiveValues<T>(arr);
// Upcast to double, set NaN as appropriate
for (int i = 0; i < arr.length(); ++i) {
*out_values++ = arr.IsNull(i) ? NAN : static_cast<double>(in_values[i]);
}
}
}
template <typename T>
inline void ConvertIntegerNoNullsSameType(const PandasOptions& options,
const ChunkedArray& data, T* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = *data.chunk(c);
if (arr.length() > 0) {
const T* in_values = GetPrimitiveValues<T>(arr);
memcpy(out_values, in_values, sizeof(T) * arr.length());
out_values += arr.length();
}
}
}
template <typename InType, typename OutType>
inline void ConvertIntegerNoNullsCast(const PandasOptions& options,
const ChunkedArray& data, OutType* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = *data.chunk(c);
const InType* in_values = GetPrimitiveValues<InType>(arr);
for (int64_t i = 0; i < arr.length(); ++i) {
*out_values = in_values[i];
}
}
}
static Status ConvertBooleanWithNulls(const PandasOptions& options,
const ChunkedArray& data, PyObject** out_values) {
PyAcquireGIL lock;
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = checked_cast<const BooleanArray&>(*data.chunk(c));
for (int64_t i = 0; i < arr.length(); ++i) {
if (arr.IsNull(i)) {
Py_INCREF(Py_None);
*out_values++ = Py_None;
} else if (arr.Value(i)) {
// True
Py_INCREF(Py_True);
*out_values++ = Py_True;
} else {
// False
Py_INCREF(Py_False);
*out_values++ = Py_False;
}
}
}
return Status::OK();
}
static void ConvertBooleanNoNulls(const PandasOptions& options, const ChunkedArray& data,
uint8_t* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = checked_cast<const BooleanArray&>(*data.chunk(c));
for (int64_t i = 0; i < arr.length(); ++i) {
*out_values++ = static_cast<uint8_t>(arr.Value(i));
}
}
}
// Generic Array -> PyObject** converter that handles object deduplication, if
// requested
template <typename ArrayType, typename WriteValue>
inline Status WriteArrayObjects(const ArrayType& arr, WriteValue&& write_func,
PyObject** out_values) {
const bool has_nulls = arr.null_count() > 0;
for (int64_t i = 0; i < arr.length(); ++i) {
if (has_nulls && arr.IsNull(i)) {
Py_INCREF(Py_None);
*out_values = Py_None;
} else {
RETURN_NOT_OK(write_func(arr.GetView(i), out_values));
}
++out_values;
}
return Status::OK();
}
template <typename T, typename Enable = void>
struct MemoizationTraits {
using Scalar = typename T::c_type;
};
template <typename T>
struct MemoizationTraits<T, enable_if_binary_like<T>> {
// For binary, we memoize string_view as a scalar value to avoid having to
// unnecessarily copy the memory into the memo table data structure
using Scalar = util::string_view;
};
template <typename Type, typename WrapFunction>
inline Status ConvertAsPyObjects(const PandasOptions& options, const ChunkedArray& data,
WrapFunction&& wrap_func, PyObject** out_values) {
using ArrayType = typename TypeTraits<Type>::ArrayType;
using Scalar = typename MemoizationTraits<Type>::Scalar;
PyAcquireGIL lock;
// TODO(fsaintjacques): propagate memory pool.
::arrow::internal::ScalarMemoTable<Scalar> memo_table(default_memory_pool());
std::vector<PyObject*> unique_values;
int32_t memo_size = 0;
auto WrapMemoized = [&](const Scalar& value, PyObject** out_values) {
int32_t memo_index = memo_table.GetOrInsert(value);
if (memo_index == memo_size) {
// New entry
RETURN_NOT_OK(wrap_func(value, out_values));
unique_values.push_back(*out_values);
++memo_size;
} else {
// Duplicate entry
Py_INCREF(unique_values[memo_index]);
*out_values = unique_values[memo_index];
}
return Status::OK();
};
auto WrapUnmemoized = [&](const Scalar& value, PyObject** out_values) {
return wrap_func(value, out_values);
};
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = checked_cast<const ArrayType&>(*data.chunk(c));
if (options.deduplicate_objects) {
RETURN_NOT_OK(WriteArrayObjects(arr, WrapMemoized, out_values));
} else {
RETURN_NOT_OK(WriteArrayObjects(arr, WrapUnmemoized, out_values));
}
out_values += arr.length();
}
return Status::OK();
}
template <typename Type>
static Status ConvertIntegerObjects(const PandasOptions& options,
const ChunkedArray& data, PyObject** out_values) {
using T = typename Type::c_type;
auto WrapValue = [](T value, PyObject** out) {
*out = std::is_signed<T>::value ? PyLong_FromLongLong(value)
: PyLong_FromUnsignedLongLong(value);
RETURN_IF_PYERROR();
return Status::OK();
};
return ConvertAsPyObjects<Type>(options, data, WrapValue, out_values);
}
template <typename Type>
inline Status ConvertBinaryLike(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
auto WrapValue = [](const util::string_view& view, PyObject** out) {
*out = WrapBytes<Type>::Wrap(view.data(), view.length());
if (*out == nullptr) {
PyErr_Clear();
return Status::UnknownError("Wrapping ", view, " failed");
}
return Status::OK();
};
return ConvertAsPyObjects<Type>(options, data, WrapValue, out_values);
}
inline Status ConvertNulls(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
PyAcquireGIL lock;
for (int c = 0; c < data.num_chunks(); c++) {
std::shared_ptr<Array> arr = data.chunk(c);
for (int64_t i = 0; i < arr->length(); ++i) {
// All values are null
Py_INCREF(Py_None);
*out_values = Py_None;
++out_values;
}
}
return Status::OK();
}
inline Status ConvertStruct(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
PyAcquireGIL lock;
if (data.num_chunks() == 0) {
return Status::OK();
}
// ChunkedArray has at least one chunk
auto arr = checked_cast<const StructArray*>(data.chunk(0).get());
// Use it to cache the struct type and number of fields for all chunks
int32_t num_fields = arr->num_fields();
auto array_type = arr->type();
std::vector<OwnedRef> fields_data(num_fields);
OwnedRef dict_item;
for (int c = 0; c < data.num_chunks(); c++) {
auto arr = checked_cast<const StructArray*>(data.chunk(c).get());
// Convert the struct arrays first
for (int32_t i = 0; i < num_fields; i++) {
PyObject* numpy_array;
RETURN_NOT_OK(ConvertArrayToPandas(options, arr->field(static_cast<int>(i)),
nullptr, &numpy_array));
fields_data[i].reset(numpy_array);
}
// Construct a dictionary for each row
const bool has_nulls = data.null_count() > 0;
for (int64_t i = 0; i < arr->length(); ++i) {
if (has_nulls && arr->IsNull(i)) {
Py_INCREF(Py_None);
*out_values = Py_None;
} else {
// Build the new dict object for the row
dict_item.reset(PyDict_New());
RETURN_IF_PYERROR();
for (int32_t field_idx = 0; field_idx < num_fields; ++field_idx) {
OwnedRef field_value;
auto name = array_type->child(static_cast<int>(field_idx))->name();
if (!arr->field(static_cast<int>(field_idx))->IsNull(i)) {
// Value exists in child array, obtain it
auto array = reinterpret_cast<PyArrayObject*>(fields_data[field_idx].obj());
auto ptr = reinterpret_cast<const char*>(PyArray_GETPTR1(array, i));
field_value.reset(PyArray_GETITEM(array, ptr));
RETURN_IF_PYERROR();
} else {
// Translate the Null to a None
Py_INCREF(Py_None);
field_value.reset(Py_None);
}
// PyDict_SetItemString increments reference count
auto setitem_result =
PyDict_SetItemString(dict_item.obj(), name.c_str(), field_value.obj());
RETURN_IF_PYERROR();
DCHECK_EQ(setitem_result, 0);
}
*out_values = dict_item.obj();
// Grant ownership to the resulting array
Py_INCREF(*out_values);
}
++out_values;
}
}
return Status::OK();
}
template <typename ArrowType>
inline Status ConvertListsLike(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
// Get column of underlying value arrays
std::vector<std::shared_ptr<Array>> value_arrays;
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = checked_cast<const ListArray&>(*data.chunk(c));
value_arrays.emplace_back(arr.values());
}
auto value_type = checked_cast<const ListType&>(*data.type()).value_type();
auto flat_column = std::make_shared<ChunkedArray>(value_arrays, value_type);
// TODO(ARROW-489): Currently we don't have a Python reference for single columns.
// Storing a reference to the whole Array would be to expensive.
OwnedRefNoGIL owned_numpy_array;
RETURN_NOT_OK(ConvertChunkedArrayToPandas(options, flat_column, nullptr,
owned_numpy_array.ref()));
PyObject* numpy_array = owned_numpy_array.obj();
PyAcquireGIL lock;
int64_t chunk_offset = 0;
for (int c = 0; c < data.num_chunks(); c++) {
auto arr = std::static_pointer_cast<ListArray>(data.chunk(c));
const bool has_nulls = data.null_count() > 0;
for (int64_t i = 0; i < arr->length(); ++i) {
if (has_nulls && arr->IsNull(i)) {
Py_INCREF(Py_None);
*out_values = Py_None;
} else {
OwnedRef start(PyLong_FromLongLong(arr->value_offset(i) + chunk_offset));
OwnedRef end(PyLong_FromLongLong(arr->value_offset(i + 1) + chunk_offset));
OwnedRef slice(PySlice_New(start.obj(), end.obj(), nullptr));
if (ARROW_PREDICT_FALSE(slice.obj() == nullptr)) {
// Fall out of loop, will return from RETURN_IF_PYERROR
break;
}
*out_values = PyObject_GetItem(numpy_array, slice.obj());
if (*out_values == nullptr) {
// Fall out of loop, will return from RETURN_IF_PYERROR
break;
}
}
++out_values;
}
RETURN_IF_PYERROR();
chunk_offset += arr->values()->length();
}
return Status::OK();
}
template <typename T>
inline void ConvertNumericNullable(const ChunkedArray& data, T na_value, T* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = *data.chunk(c);
const T* in_values = GetPrimitiveValues<T>(arr);
if (arr.null_count() > 0) {
for (int64_t i = 0; i < arr.length(); ++i) {
*out_values++ = arr.IsNull(i) ? na_value : in_values[i];
}
} else {
memcpy(out_values, in_values, sizeof(T) * arr.length());
out_values += arr.length();
}
}
}
template <typename InType, typename OutType>
inline void ConvertNumericNullableCast(const ChunkedArray& data, OutType na_value,
OutType* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = *data.chunk(c);
const InType* in_values = GetPrimitiveValues<InType>(arr);
for (int64_t i = 0; i < arr.length(); ++i) {
*out_values++ = arr.IsNull(i) ? na_value : static_cast<OutType>(in_values[i]);
}
}
}
template <typename T, int64_t SHIFT>
inline void ConvertDatetimeNanos(const ChunkedArray& data, int64_t* out_values) {
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = *data.chunk(c);
const T* in_values = GetPrimitiveValues<T>(arr);
for (int64_t i = 0; i < arr.length(); ++i) {
*out_values++ = arr.IsNull(i) ? kPandasTimestampNull
: (static_cast<int64_t>(in_values[i]) * SHIFT);
}
}
}
template <typename Type>
static Status ConvertDates(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
auto WrapValue = [](typename Type::c_type value, PyObject** out) {
RETURN_NOT_OK(internal::PyDate_from_int(value, Type::UNIT, out));
RETURN_IF_PYERROR();
return Status::OK();
};
return ConvertAsPyObjects<Type>(options, data, WrapValue, out_values);
}
template <typename Type>
static Status ConvertTimes(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
const TimeUnit::type unit = checked_cast<const Type&>(*data.type()).unit();
auto WrapValue = [unit](typename Type::c_type value, PyObject** out) {
RETURN_NOT_OK(internal::PyTime_from_int(value, unit, out));
RETURN_IF_PYERROR();
return Status::OK();
};
return ConvertAsPyObjects<Type>(options, data, WrapValue, out_values);
}
static Status ConvertDecimals(const PandasOptions& options, const ChunkedArray& data,
PyObject** out_values) {
PyAcquireGIL lock;
OwnedRef decimal;
OwnedRef Decimal;
RETURN_NOT_OK(internal::ImportModule("decimal", &decimal));
RETURN_NOT_OK(internal::ImportFromModule(decimal.obj(), "Decimal", &Decimal));
PyObject* decimal_constructor = Decimal.obj();
for (int c = 0; c < data.num_chunks(); c++) {
const auto& arr = checked_cast<const arrow::Decimal128Array&>(*data.chunk(c));
for (int64_t i = 0; i < arr.length(); ++i) {
if (arr.IsNull(i)) {
Py_INCREF(Py_None);
*out_values++ = Py_None;
} else {
*out_values++ =
internal::DecimalFromString(decimal_constructor, arr.FormatValue(i));
RETURN_IF_PYERROR();
}
}
}
return Status::OK();
}
#define CONVERTLISTSLIKE_CASE(ArrowType, ArrowEnum) \
case Type::ArrowEnum: \
RETURN_NOT_OK((ConvertListsLike<ArrowType>(options_, *data, out_buffer))); \
break;
class ObjectBlock : public PandasBlock {
public:
using PandasBlock::PandasBlock;
Status Allocate() override { return AllocateNDArray(NPY_OBJECT); }
Status Write(std::shared_ptr<ChunkedArray> data, int64_t abs_placement,
int64_t rel_placement) override {
Type::type type = data->type()->id();
PyObject** out_buffer =
reinterpret_cast<PyObject**>(block_data_) + rel_placement * num_rows_;
if (type == Type::BOOL) {
RETURN_NOT_OK(ConvertBooleanWithNulls(options_, *data, out_buffer));
} else if (type == Type::UINT8) {
RETURN_NOT_OK(ConvertIntegerObjects<UInt8Type>(options_, *data, out_buffer));
} else if (type == Type::INT8) {
RETURN_NOT_OK(ConvertIntegerObjects<Int8Type>(options_, *data, out_buffer));
} else if (type == Type::UINT16) {
RETURN_NOT_OK(ConvertIntegerObjects<UInt16Type>(options_, *data, out_buffer));
} else if (type == Type::INT16) {
RETURN_NOT_OK(ConvertIntegerObjects<Int16Type>(options_, *data, out_buffer));
} else if (type == Type::UINT32) {
RETURN_NOT_OK(ConvertIntegerObjects<UInt32Type>(options_, *data, out_buffer));
} else if (type == Type::INT32) {
RETURN_NOT_OK(ConvertIntegerObjects<Int32Type>(options_, *data, out_buffer));
} else if (type == Type::UINT64) {
RETURN_NOT_OK(ConvertIntegerObjects<UInt64Type>(options_, *data, out_buffer));
} else if (type == Type::INT64) {
RETURN_NOT_OK(ConvertIntegerObjects<Int64Type>(options_, *data, out_buffer));
} else if (type == Type::BINARY) {
RETURN_NOT_OK(ConvertBinaryLike<BinaryType>(options_, *data, out_buffer));
} else if (type == Type::LARGE_BINARY) {
RETURN_NOT_OK(ConvertBinaryLike<LargeBinaryType>(options_, *data, out_buffer));
} else if (type == Type::STRING) {
RETURN_NOT_OK(ConvertBinaryLike<StringType>(options_, *data, out_buffer));
} else if (type == Type::LARGE_STRING) {
RETURN_NOT_OK(ConvertBinaryLike<LargeStringType>(options_, *data, out_buffer));
} else if (type == Type::FIXED_SIZE_BINARY) {
RETURN_NOT_OK(ConvertBinaryLike<FixedSizeBinaryType>(options_, *data, out_buffer));
} else if (type == Type::DATE32) {
RETURN_NOT_OK(ConvertDates<Date32Type>(options_, *data, out_buffer));
} else if (type == Type::DATE64) {
RETURN_NOT_OK(ConvertDates<Date64Type>(options_, *data, out_buffer));
} else if (type == Type::TIME32) {
RETURN_NOT_OK(ConvertTimes<Time32Type>(options_, *data, out_buffer));
} else if (type == Type::TIME64) {
RETURN_NOT_OK(ConvertTimes<Time64Type>(options_, *data, out_buffer));
} else if (type == Type::DECIMAL) {
RETURN_NOT_OK(ConvertDecimals(options_, *data, out_buffer));
} else if (type == Type::NA) {
RETURN_NOT_OK(ConvertNulls(options_, *data, out_buffer));
} else if (type == Type::LIST) {
auto list_type = std::static_pointer_cast<ListType>(data->type());
switch (list_type->value_type()->id()) {
CONVERTLISTSLIKE_CASE(BooleanType, BOOL)
CONVERTLISTSLIKE_CASE(UInt8Type, UINT8)
CONVERTLISTSLIKE_CASE(Int8Type, INT8)
CONVERTLISTSLIKE_CASE(UInt16Type, UINT16)
CONVERTLISTSLIKE_CASE(Int16Type, INT16)
CONVERTLISTSLIKE_CASE(UInt32Type, UINT32)
CONVERTLISTSLIKE_CASE(Int32Type, INT32)
CONVERTLISTSLIKE_CASE(UInt64Type, UINT64)
CONVERTLISTSLIKE_CASE(Int64Type, INT64)
CONVERTLISTSLIKE_CASE(Date32Type, DATE32)
CONVERTLISTSLIKE_CASE(Date64Type, DATE64)
CONVERTLISTSLIKE_CASE(Time32Type, TIME32)
CONVERTLISTSLIKE_CASE(Time64Type, TIME64)
CONVERTLISTSLIKE_CASE(TimestampType, TIMESTAMP)
CONVERTLISTSLIKE_CASE(FloatType, FLOAT)
CONVERTLISTSLIKE_CASE(DoubleType, DOUBLE)
CONVERTLISTSLIKE_CASE(DecimalType, DECIMAL)
CONVERTLISTSLIKE_CASE(BinaryType, BINARY)
CONVERTLISTSLIKE_CASE(StringType, STRING)
CONVERTLISTSLIKE_CASE(ListType, LIST)
CONVERTLISTSLIKE_CASE(NullType, NA)
default: {
return Status::NotImplemented(
"Not implemented type for conversion from List to Pandas ObjectBlock: ",
list_type->value_type()->ToString());
}
}
} else if (type == Type::STRUCT) {
RETURN_NOT_OK(ConvertStruct(options_, *data, out_buffer));
} else {
return Status::NotImplemented("Unsupported type for object array output: ",
data->type()->ToString());
}
placement_data_[rel_placement] = abs_placement;
return Status::OK();
}
};
template <int ARROW_TYPE, typename C_TYPE>
class IntBlock : public PandasBlock {
public:
using PandasBlock::PandasBlock;
Status Allocate() override {
return AllocateNDArray(internal::arrow_traits<ARROW_TYPE>::npy_type);
}
Status Write(std::shared_ptr<ChunkedArray> data, int64_t abs_placement,
int64_t rel_placement) override {
Type::type type = data->type()->id();
C_TYPE* out_buffer =
reinterpret_cast<C_TYPE*>(block_data_) + rel_placement * num_rows_;
if (type != ARROW_TYPE) {
return Status::NotImplemented("Cannot write Arrow data of type ",
data->type()->ToString(), " to a Pandas int",
sizeof(C_TYPE), " block");
}
ConvertIntegerNoNullsSameType<C_TYPE>(options_, *data, out_buffer);
placement_data_[rel_placement] = abs_placement;
return Status::OK();
}
};
using UInt8Block = IntBlock<Type::UINT8, uint8_t>;
using Int8Block = IntBlock<Type::INT8, int8_t>;
using UInt16Block = IntBlock<Type::UINT16, uint16_t>;
using Int16Block = IntBlock<Type::INT16, int16_t>;
using UInt32Block = IntBlock<Type::UINT32, uint32_t>;
using Int32Block = IntBlock<Type::INT32, int32_t>;
using UInt64Block = IntBlock<Type::UINT64, uint64_t>;
using Int64Block = IntBlock<Type::INT64, int64_t>;
class Float16Block : public PandasBlock {
public:
using PandasBlock::PandasBlock;
Status Allocate() override { return AllocateNDArray(NPY_FLOAT16); }
Status Write(std::shared_ptr<ChunkedArray> data, int64_t abs_placement,
int64_t rel_placement) override {
Type::type type = data->type()->id();
if (type != Type::HALF_FLOAT) {
return Status::NotImplemented("Cannot write Arrow data of type ",
data->type()->ToString(),
" to a Pandas float16 block");
}
npy_half* out_buffer =
reinterpret_cast<npy_half*>(block_data_) + rel_placement * num_rows_;
ConvertNumericNullable<npy_half>(*data, NPY_HALF_NAN, out_buffer);
placement_data_[rel_placement] = abs_placement;
return Status::OK();
}
};
class Float32Block : public PandasBlock {
public:
using PandasBlock::PandasBlock;
Status Allocate() override { return AllocateNDArray(NPY_FLOAT32); }
Status Write(std::shared_ptr<ChunkedArray> data, int64_t abs_placement,
int64_t rel_placement) override {
Type::type type = data->type()->id();
if (type != Type::FLOAT) {
return Status::NotImplemented("Cannot write Arrow data of type ",
data->type()->ToString(),
" to a Pandas float32 block");
}
float* out_buffer = reinterpret_cast<float*>(block_data_) + rel_placement * num_rows_;
ConvertNumericNullable<float>(*data, NAN, out_buffer);
placement_data_[rel_placement] = abs_placement;
return Status::OK();
}
};
class Float64Block : public PandasBlock {
public:
using PandasBlock::PandasBlock;
Status Allocate() override { return AllocateNDArray(NPY_FLOAT64); }
Status Write(std::shared_ptr<ChunkedArray> data, int64_t abs_placement,
int64_t rel_placement) override {
Type::type type = data->type()->id();
double* out_buffer =
reinterpret_cast<double*>(block_data_) + rel_placement * num_rows_;
#define INTEGER_CASE(IN_TYPE) \
ConvertIntegerWithNulls<IN_TYPE>(options_, *data, out_buffer); \
break;
switch (type) {
case Type::UINT8:
INTEGER_CASE(uint8_t);
case Type::INT8:
INTEGER_CASE(int8_t);
case Type::UINT16:
INTEGER_CASE(uint16_t);
case Type::INT16:
INTEGER_CASE(int16_t);
case Type::UINT32:
INTEGER_CASE(uint32_t);
case Type::INT32:
INTEGER_CASE(int32_t);
case Type::UINT64:
INTEGER_CASE(uint64_t);
case Type::INT64:
INTEGER_CASE(int64_t);
case Type::FLOAT:
ConvertNumericNullableCast<float, double>(*data, NAN, out_buffer);
break;
case Type::DOUBLE:
ConvertNumericNullable<double>(*data, NAN, out_buffer);
break;
default:
return Status::NotImplemented("Cannot write Arrow data of type ",
data->type()->ToString(),
" to a Pandas float64 block");
}