Repository navigation
GH-34729: [C++][Python] Enhanced Arrow<->Pandas map/pydict support #34730
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
c9114aa
02d0fc1
f067333
5328035
20a2cb0
53cdb4a
d7c7764
58e7ddc
092793a
f0dd00a
551990b
69ee841
ddd6764
9e1dec0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -176,6 +176,7 @@ static inline bool ListTypeSupported(const DataType& type) { | |
| case Type::DATE32: | ||
| case Type::DATE64: | ||
| case Type::STRUCT: | ||
| case Type::MAP: | ||
| case Type::TIME32: | ||
| case Type::TIME64: | ||
| case Type::TIMESTAMP: | ||
|
|
@@ -807,52 +808,20 @@ Status ConvertListsLike(PandasOptions options, const ChunkedArray& data, | |
| return Status::OK(); | ||
| } | ||
|
|
||
| Status ConvertMap(PandasOptions options, const ChunkedArray& data, | ||
| PyObject** out_values) { | ||
| // Get columns of underlying key/item arrays | ||
| std::vector<std::shared_ptr<Array>> key_arrays; | ||
| std::vector<std::shared_ptr<Array>> item_arrays; | ||
| for (int c = 0; c < data.num_chunks(); ++c) { | ||
| const auto& map_arr = checked_cast<const MapArray&>(*data.chunk(c)); | ||
| key_arrays.emplace_back(map_arr.keys()); | ||
| item_arrays.emplace_back(map_arr.items()); | ||
| } | ||
|
|
||
| const auto& map_type = checked_cast<const MapType&>(*data.type()); | ||
| auto key_type = map_type.key_type(); | ||
| auto item_type = map_type.item_type(); | ||
|
|
||
| // ARROW-6899: Convert dictionary-encoded children to dense instead of | ||
| // failing below. A more efficient conversion than this could be done later | ||
| if (key_type->id() == Type::DICTIONARY) { | ||
| auto dense_type = checked_cast<const DictionaryType&>(*key_type).value_type(); | ||
| RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &key_arrays)); | ||
| key_type = dense_type; | ||
| } | ||
| if (item_type->id() == Type::DICTIONARY) { | ||
| auto dense_type = checked_cast<const DictionaryType&>(*item_type).value_type(); | ||
| RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &item_arrays)); | ||
| item_type = dense_type; | ||
| } | ||
| template<typename F1, typename F2, typename F3> | ||
| Status ConvertMapHelper( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this change makes sense when combined with the next commit |
||
| F1 resetRow, | ||
| F2 addPairToRow, | ||
| F3 stealRow, | ||
| const ChunkedArray& data, | ||
| PyArrayObject* py_keys, | ||
| PyArrayObject* py_items, | ||
| // needed for null checks in items | ||
| const std::vector<std::shared_ptr<Array>> item_arrays, | ||
| PyObject** out_values) { | ||
|
|
||
| // See notes in MakeInnerOptions. | ||
| options = MakeInnerOptions(std::move(options)); | ||
| // Don't blindly convert because timestamps in lists are handled differently. | ||
| options.timestamp_as_object = true; | ||
|
|
||
| auto flat_keys = std::make_shared<ChunkedArray>(key_arrays, key_type); | ||
| auto flat_items = std::make_shared<ChunkedArray>(item_arrays, item_type); | ||
| OwnedRef list_item; | ||
| OwnedRef key_value; | ||
| OwnedRef item_value; | ||
| OwnedRefNoGIL owned_numpy_keys; | ||
| RETURN_NOT_OK( | ||
| ConvertChunkedArrayToPandas(options, flat_keys, nullptr, owned_numpy_keys.ref())); | ||
| OwnedRefNoGIL owned_numpy_items; | ||
| RETURN_NOT_OK( | ||
| ConvertChunkedArrayToPandas(options, flat_items, nullptr, owned_numpy_items.ref())); | ||
| PyArrayObject* py_keys = reinterpret_cast<PyArrayObject*>(owned_numpy_keys.obj()); | ||
| PyArrayObject* py_items = reinterpret_cast<PyArrayObject*>(owned_numpy_items.obj()); | ||
|
|
||
| int64_t chunk_offset = 0; | ||
| for (int c = 0; c < data.num_chunks(); ++c) { | ||
|
|
@@ -866,14 +835,13 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, | |
| *out_values = Py_None; | ||
| } else { | ||
| int64_t entry_offset = arr.value_offset(i); | ||
| int64_t num_maps = arr.value_offset(i + 1) - entry_offset; | ||
| int64_t num_pairs = arr.value_offset(i + 1) - entry_offset; | ||
|
|
||
| // Build the new list object for the row of maps | ||
| list_item.reset(PyList_New(num_maps)); | ||
| RETURN_IF_PYERROR(); | ||
| // Build the new list object for the row of Python pairs | ||
| RETURN_NOT_OK(resetRow(num_pairs)); | ||
|
|
||
| // Add each key/item pair in the row | ||
| for (int64_t j = 0; j < num_maps; ++j) { | ||
| for (int64_t j = 0; j < num_pairs; ++j) { | ||
| // Get key value, key is non-nullable for a valid row | ||
| auto ptr_key = reinterpret_cast<const char*>( | ||
| PyArray_GETPTR1(py_keys, chunk_offset + entry_offset + j)); | ||
|
|
@@ -892,14 +860,12 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, | |
| RETURN_IF_PYERROR(); | ||
| } | ||
|
|
||
| // Add the key/item pair to the list for the row | ||
| PyList_SET_ITEM(list_item.obj(), j, | ||
| PyTuple_Pack(2, key_value.obj(), item_value.obj())); | ||
| RETURN_IF_PYERROR(); | ||
| // Add the key/item pair to the row | ||
| RETURN_NOT_OK(addPairToRow(j, key_value, item_value)); | ||
| } | ||
|
|
||
| // Pass ownership to the resulting array | ||
| *out_values = list_item.detach(); | ||
| *out_values = stealRow(); | ||
| } | ||
| ++out_values; | ||
| } | ||
|
|
@@ -911,6 +877,166 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, | |
| return Status::OK(); | ||
| } | ||
|
|
||
| // A more helpful error message around TypeErrors that may stem from unhashable keys | ||
| Status CheckMapAsPydictsTypeError() { | ||
| if (ARROW_PREDICT_TRUE(!PyErr_Occurred())) { | ||
| return Status::OK(); | ||
| } | ||
| if (PyErr_ExceptionMatches(PyExc_TypeError)) { | ||
| // Modify the error string directly, so it is re-raised | ||
| // with our additional info. | ||
| // | ||
| // There are not many interesting things happening when this | ||
| // is hit. This is intended to only be called directly after | ||
| // PyDict_SetItem, where a finite set of errors could occur. | ||
| PyObject *type, *value, *traceback; | ||
| PyErr_Fetch(&type, &value, &traceback); | ||
| std::string message; | ||
| RETURN_NOT_OK(internal::PyObject_StdStringStr(value, &message)); | ||
| message += ". If keys are not hashable, then you must use the option " | ||
| "[maps_as_pydicts=None (default)]"; | ||
|
|
||
| // resets the error | ||
| PyErr_SetString(PyExc_TypeError, message.c_str()); | ||
| } | ||
| return ConvertPyError(); | ||
| } | ||
|
|
||
| Status CheckForDuplicateKeys(bool error_on_duplicate_keys, | ||
| Py_ssize_t total_dict_len, Py_ssize_t total_raw_len) { | ||
| if (total_dict_len < total_raw_len) { | ||
| const char* message = | ||
| "[maps_as_pydicts] " | ||
| "After conversion of Arrow maps to pydicts, " | ||
| "detected data loss due to duplicate keys. " | ||
| "Original input length is [%lld], total converted pydict length is [%lld]."; | ||
| std::array<char, 256> buf; | ||
| std::snprintf(buf.data(), buf.size(), message, total_raw_len, total_dict_len); | ||
|
|
||
| if (error_on_duplicate_keys) { | ||
| return Status::UnknownError(buf.data()); | ||
| } else { | ||
| ARROW_LOG(WARNING) << buf.data(); | ||
| } | ||
| } | ||
| return Status::OK(); | ||
| } | ||
|
|
||
| Status ConvertMap(PandasOptions options, const ChunkedArray& data, | ||
| PyObject** out_values) { | ||
| // Get columns of underlying key/item arrays | ||
| std::vector<std::shared_ptr<Array>> key_arrays; | ||
| std::vector<std::shared_ptr<Array>> item_arrays; | ||
| for (int c = 0; c < data.num_chunks(); ++c) { | ||
| const auto& map_arr = checked_cast<const MapArray&>(*data.chunk(c)); | ||
| key_arrays.emplace_back(map_arr.keys()); | ||
| item_arrays.emplace_back(map_arr.items()); | ||
| } | ||
|
|
||
| const auto& map_type = checked_cast<const MapType&>(*data.type()); | ||
| auto key_type = map_type.key_type(); | ||
| auto item_type = map_type.item_type(); | ||
|
|
||
| // ARROW-6899: Convert dictionary-encoded children to dense instead of | ||
| // failing below. A more efficient conversion than this could be done later | ||
| if (key_type->id() == Type::DICTIONARY) { | ||
| auto dense_type = checked_cast<const DictionaryType&>(*key_type).value_type(); | ||
| RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &key_arrays)); | ||
| key_type = dense_type; | ||
| } | ||
| if (item_type->id() == Type::DICTIONARY) { | ||
| auto dense_type = checked_cast<const DictionaryType&>(*item_type).value_type(); | ||
| RETURN_NOT_OK(DecodeDictionaries(options.pool, dense_type, &item_arrays)); | ||
| item_type = dense_type; | ||
| } | ||
|
|
||
| // See notes in MakeInnerOptions. | ||
| options = MakeInnerOptions(std::move(options)); | ||
| // Don't blindly convert because timestamps in lists are handled differently. | ||
| options.timestamp_as_object = true; | ||
|
|
||
| auto flat_keys = std::make_shared<ChunkedArray>(key_arrays, key_type); | ||
| auto flat_items = std::make_shared<ChunkedArray>(item_arrays, item_type); | ||
| OwnedRefNoGIL owned_numpy_keys; | ||
| RETURN_NOT_OK( | ||
| ConvertChunkedArrayToPandas(options, flat_keys, nullptr, owned_numpy_keys.ref())); | ||
| OwnedRefNoGIL owned_numpy_items; | ||
| RETURN_NOT_OK( | ||
| ConvertChunkedArrayToPandas(options, flat_items, nullptr, owned_numpy_items.ref())); | ||
| PyArrayObject* py_keys = reinterpret_cast<PyArrayObject*>(owned_numpy_keys.obj()); | ||
| PyArrayObject* py_items = reinterpret_cast<PyArrayObject*>(owned_numpy_items.obj()); | ||
|
|
||
| if (options.maps_as_pydicts == MapConversionType::DEFAULT) { | ||
| // The default behavior to express an Arrow MAP as a list of [(key, value), ...] pairs | ||
| OwnedRef list_item; | ||
| return ConvertMapHelper( | ||
| [&list_item](int64_t num_pairs) { | ||
| list_item.reset(PyList_New(num_pairs)); | ||
| return CheckPyError(); | ||
| }, | ||
| [&list_item](int64_t idx, OwnedRef& key_value, OwnedRef& item_value) { | ||
| PyList_SET_ITEM(list_item.obj(), idx, | ||
| PyTuple_Pack(2, key_value.obj(), item_value.obj())); | ||
| return CheckPyError(); | ||
| }, | ||
| [&list_item]{ return list_item.detach(); }, | ||
| data, | ||
| py_keys, | ||
| py_items, | ||
| item_arrays, | ||
| out_values); | ||
| } else { | ||
| // Use a native pydict | ||
| OwnedRef dict_item; | ||
| Py_ssize_t total_dict_len{0}; | ||
| Py_ssize_t total_raw_len{0}; | ||
|
|
||
| bool error_on_duplicate_keys; | ||
| if (options.maps_as_pydicts == MapConversionType::LOSSY) { | ||
| error_on_duplicate_keys = false; | ||
| } else if (options.maps_as_pydicts == MapConversionType::STRICT_) { | ||
| error_on_duplicate_keys = true; | ||
| } else { | ||
| auto val = std::underlying_type_t<MapConversionType>(options.maps_as_pydicts); | ||
| return Status::UnknownError( | ||
| "Received unknown option for maps_as_pydicts: " + std::to_string(val) | ||
| ); | ||
| } | ||
|
|
||
| auto status = ConvertMapHelper( | ||
| [&dict_item, &total_raw_len](int64_t num_pairs) { | ||
| total_raw_len += num_pairs; | ||
| dict_item.reset(PyDict_New()); | ||
| return CheckPyError(); | ||
| }, | ||
| [&dict_item]([[maybe_unused]] int64_t idx, OwnedRef& key_value, OwnedRef& item_value) { | ||
| auto setitem_result = | ||
| PyDict_SetItem(dict_item.obj(), key_value.obj(), item_value.obj()); | ||
| ARROW_RETURN_NOT_OK(CheckMapAsPydictsTypeError()); | ||
| // returns -1 if there are internal errors around hashing/resizing | ||
| return setitem_result == 0 ? | ||
| Status::OK() : | ||
| Status::UnknownError("[maps_as_pydicts] " | ||
| "Unexpected failure inserting Arrow (key, value) pair into Python dict" | ||
| ); | ||
| }, | ||
| [&dict_item, &total_dict_len]{ | ||
| total_dict_len += PyDict_Size(dict_item.obj()); | ||
| return dict_item.detach(); | ||
| }, | ||
| data, | ||
| py_keys, | ||
| py_items, | ||
| item_arrays, | ||
| out_values); | ||
|
|
||
| ARROW_RETURN_NOT_OK(status); | ||
| // If there were no errors generating the pydicts, | ||
| // then check if we detected any data loss from duplicate keys. | ||
| return CheckForDuplicateKeys(error_on_duplicate_keys, total_dict_len, total_raw_len); | ||
| } | ||
| } | ||
|
|
||
| template <typename InType, typename OutType> | ||
| inline void ConvertNumericNullable(const ChunkedArray& data, InType na_value, | ||
| OutType* out_values) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -762,7 +762,7 @@ class PyListConverter : public ListConverter<T, PyConverter, PyConverterTrait> { | |
| RETURN_NOT_OK(AppendSequence(value)); | ||
| } else if (PySet_Check(value) || (Py_TYPE(value) == &PyDictValues_Type)) { | ||
| RETURN_NOT_OK(AppendIterable(value)); | ||
| } else if (PyDict_Check(value) && this->options_.type->id() == Type::MAP) { | ||
| } else if (PyDict_Check(value) && this->type()->id() == Type::MAP) { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like So, when there's a nested map (e.g. list of map):
That causes this check to fail unexpected, since the pydict is seen as having I am unsure what the expected behavior of
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed. |
||
| // Branch to support Python Dict with `map` DataType. | ||
| auto items = PyDict_Items(value); | ||
| OwnedRef item_ref(items); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There didn't seem to be a strong reason to have this disabled. Users can do nested maps via (list of structs of maps)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed. Although it's interesting we check the value type for list, but not the fields of structs? I was thinking you should put
Type::MAPdown withType::LIST, since it is a subclass of ListType, though since the immediate child isType::STRUCTright now it won't do anything meaningful.