From c9114aa5e8511b1449976d5be68cda82222f91ab Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sat, 25 Mar 2023 08:05:16 -0400 Subject: [PATCH 01/14] [C++/Python] Support conversion of list of maps to pandas --- .../src/arrow/python/arrow_to_pandas.cc | 1 + python/pyarrow/tests/test_pandas.py | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index eac657fb8fd1..27791714d452 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -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: diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index a49552aa0a21..d863e23a6ea6 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -2135,6 +2135,33 @@ def test_to_list_of_structs_pandas(self): DeprecationWarning) tm.assert_series_equal(series, expected) + def test_to_list_of_maps_pandas(self): + if ((Version(np.__version__) >= Version("1.25.0.dev0")) and + (Version(pd.__version__) < Version("2.0.0"))): + # TODO: regression in pandas with numpy 1.25dev + # https://github.com/pandas-dev/pandas/issues/50360 + pytest.skip("Regression in pandas with numpy 1.25") + offsets = pa.array([0, 2, 5, 6], pa.int32()) + keys = pa.array(['foo', 'bar', 'baz', 'qux', 'quux', 'quz']) + items = pa.array([['a', 'b'], ['c', 'd'], [], None, [None, 'e'], ['f', 'g']], + pa.list_(pa.string())) + maps = pa.MapArray.from_arrays(offsets, keys, items) + data = pa.ListArray.from_arrays([0, 1, 3], maps) + + expected = pd.Series([ + [[('foo', ['a', 'b']), ('bar', ['c', 'd'])]], + [[('baz', []), ('qux', None), ('quux', [None, 'e'])], [('quz', ['f', 'g'])]] + ]) + + series = pd.Series(data.to_pandas()) + + # pandas.testing generates a + # DeprecationWarning: elementwise comparison failed + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "elementwise comparison failed", + DeprecationWarning) + tm.assert_series_equal(series, expected) + @pytest.mark.parametrize('t,data,expected', [ ( pa.int64, From 02d0fc1e01bf6637486d188c29c37929007bdb84 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sat, 25 Mar 2023 12:20:16 -0400 Subject: [PATCH 02/14] [C++/Python] Refactor ConvertMaps to generalize row type --- .../src/arrow/python/arrow_to_pandas.cc | 135 +++++++++++------- 1 file changed, 82 insertions(+), 53 deletions(-) diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index 27791714d452..32e3e74c1888 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -808,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> key_arrays; - std::vector> item_arrays; - for (int c = 0; c < data.num_chunks(); ++c) { - const auto& map_arr = checked_cast(*data.chunk(c)); - key_arrays.emplace_back(map_arr.keys()); - item_arrays.emplace_back(map_arr.items()); - } - - const auto& map_type = checked_cast(*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(*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(*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; +template +Status ConvertMapHelper( + F1 resetRow, + F2 addPairToRow, + F3 stealRow, + const ChunkedArray& data, + PyArrayObject* py_keys, + PyArrayObject* py_items, + // needed for null checks in items + const std::vector> item_arrays, + PyObject** out_values) { - auto flat_keys = std::make_shared(key_arrays, key_type); - auto flat_items = std::make_shared(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(owned_numpy_keys.obj()); - PyArrayObject* py_items = reinterpret_cast(owned_numpy_items.obj()); int64_t chunk_offset = 0; for (int c = 0; c < data.num_chunks(); ++c) { @@ -867,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( PyArray_GETPTR1(py_keys, chunk_offset + entry_offset + j)); @@ -893,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; } @@ -912,6 +877,70 @@ Status ConvertMap(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> key_arrays; + std::vector> item_arrays; + for (int c = 0; c < data.num_chunks(); ++c) { + const auto& map_arr = checked_cast(*data.chunk(c)); + key_arrays.emplace_back(map_arr.keys()); + item_arrays.emplace_back(map_arr.items()); + } + + const auto& map_type = checked_cast(*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(*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(*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(key_arrays, key_type); + auto flat_items = std::make_shared(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(owned_numpy_keys.obj()); + PyArrayObject* py_items = reinterpret_cast(owned_numpy_items.obj()); + + // 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); +} + template inline void ConvertNumericNullable(const ChunkedArray& data, InType na_value, OutType* out_values) { From f0673335cbc0d8c229790bb1a6d2056e5af78a3b Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sat, 25 Mar 2023 12:58:15 -0400 Subject: [PATCH 03/14] [C++/Python] Support option to convert maps to native pydicts --- python/pyarrow/array.pxi | 12 +++- python/pyarrow/includes/libarrow_python.pxd | 1 + .../src/arrow/python/arrow_to_pandas.cc | 63 +++++++++++++------ .../src/arrow/python/arrow_to_pandas.h | 8 +++ python/pyarrow/tests/test_pandas.py | 33 ++++++++++ 5 files changed, 98 insertions(+), 19 deletions(-) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index 11f10dddef30..29cf8a3c6248 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -699,6 +699,7 @@ cdef class _PandasConvertible(_Weakrefable): bint safe=True, bint split_blocks=False, bint self_destruct=False, + bint maps_as_pydicts=False, types_mapper=None ): """ @@ -753,6 +754,13 @@ cdef class _PandasConvertible(_Weakrefable): Note that you may not see always memory usage improvements. For example, if multiple columns share an underlying allocation, memory can't be freed until all columns are converted. + maps_as_pydicts : bool, default False + If true, convert Arrow Map arrays to native Python dicts. + This can change the ordering of (key, value) pairs, and will + deduplicate multiple keys, resulting in a possible loss of data. + The default behavior (false), is to convert Arrow Map arrays to + Python list-of-tuples in the same order as the Arrow Map, as in + [(key1, value1), (key2, value2), ...] types_mapper : function, default None A function mapping a pyarrow DataType to a pandas ExtensionDtype. This can be used to override the default pandas type for conversion @@ -832,7 +840,8 @@ cdef class _PandasConvertible(_Weakrefable): deduplicate_objects=deduplicate_objects, safe=safe, split_blocks=split_blocks, - self_destruct=self_destruct + self_destruct=self_destruct, + maps_as_pydicts=maps_as_pydicts ) return self._to_pandas(options, categories=categories, ignore_metadata=ignore_metadata, @@ -853,6 +862,7 @@ cdef PandasOptions _convert_pandas_options(dict options): result.split_blocks = options['split_blocks'] result.self_destruct = options['self_destruct'] result.ignore_timezone = os.environ.get('PYARROW_IGNORE_TIMEZONE', False) + result.maps_as_pydicts = options['maps_as_pydicts'] return result diff --git a/python/pyarrow/includes/libarrow_python.pxd b/python/pyarrow/includes/libarrow_python.pxd index f29c336bd0d0..7999f0a493ec 100644 --- a/python/pyarrow/includes/libarrow_python.pxd +++ b/python/pyarrow/includes/libarrow_python.pxd @@ -186,6 +186,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: c_bool safe_cast c_bool split_blocks c_bool self_destruct + c_bool maps_as_pydicts c_bool decode_dictionaries unordered_set[c_string] categorical_columns unordered_set[c_string] extension_columns diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index 32e3e74c1888..d52a40f0a1d8 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -921,24 +921,51 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, PyArrayObject* py_keys = reinterpret_cast(owned_numpy_keys.obj()); PyArrayObject* py_items = reinterpret_cast(owned_numpy_items.obj()); - // 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); + if (!options.maps_as_pydicts) { + // 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; + return ConvertMapHelper( + [&dict_item]([[maybe_unused]] int64_t) { + 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()); + RETURN_IF_PYERROR(); + // returns -1 if there are internal errors around hashing/resizing + return setitem_result == 0 ? + Status::OK() : + Status::UnknownError( + "Unexpected failure inserting Arrow (key, value) pair into Python dict" + ); + }, + [&dict_item]{ return dict_item.detach(); }, + data, + py_keys, + py_items, + item_arrays, + out_values); + } } template diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.h b/python/pyarrow/src/arrow/python/arrow_to_pandas.h index 6570364b8d2a..20e8ee6504df 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.h +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.h @@ -90,6 +90,14 @@ struct PandasOptions { /// conversions bool self_destruct = false; + /// \brief If true, convert Arrow Map arrays to native Python dicts. + /// This can change the ordering of (key, value) pairs, and will deduplicate + /// multiple keys, resulting in a possible loss of data. + /// The default behavior (false), is to convert Arrow Map arrays to Python + /// list-of-tuples in the same order as the Arrow Map, + /// as in [(key1, value1), (key2, value2), ...] + bool maps_as_pydicts = false; + // Used internally for nested arrays. bool decode_dictionaries = false; diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index d863e23a6ea6..e6de3113dee0 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -4576,3 +4576,36 @@ def test_does_not_mutate_timedelta_nested(): df = table.to_pandas() assert df["timedelta_2"][0].to_pytimedelta() == timedelta_2[0] + + +def test_roundtrip_nested_map_table_with_pydicts(): + schema = pa.schema([pa.field("a", pa.list_(pa.map_(pa.int8(), pa.struct([pa.field("b", pa.binary())]))))]) + table = pa.table([[ + [[(1, None)]], + None, + [ + [(2, {"b": b"abc"})], + [(3, {"b": None}), (4, {"b": b"def"})], + ] + ]], + schema=schema, + ) + + expected_default_df = pd.DataFrame( + {"a": [[[(1, None)]], None, [[(2, {"b": b"abc"})], [(3, {"b": None}), (4, {"b": b"def"})]]]} + ) + expected_as_pydicts_df = pd.DataFrame( + {"a": [[{1: None}], None, [{2: {"b": b"abc"}}, {3: {"b": None}, 4: {"b": b"def"}}]]} + ) + + default_df = table.to_pandas() + as_pydicts_df = table.to_pandas(maps_as_pydicts=True) + + tm.assert_frame_equal(default_df, expected_default_df) + tm.assert_frame_equal(as_pydicts_df, expected_as_pydicts_df) + + table_default_roundtrip = pa.Table.from_pandas(default_df, schema=schema) + assert table.equals(table_default_roundtrip) + + with pytest.raises(pa.ArrowTypeError): + table_as_pydicts_roundtrip = pa.Table.from_pandas(as_pydicts_df, schema=schema) \ No newline at end of file From 532803530cc74ad04541533534dda0e6508435a8 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sun, 26 Mar 2023 01:11:57 -0400 Subject: [PATCH 04/14] [C++/Python] Fix bug preventing nested pydict to arrow conversion --- .../src/arrow/python/python_to_arrow.cc | 2 +- python/pyarrow/tests/test_pandas.py | 26 ++++++++++--------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/python/pyarrow/src/arrow/python/python_to_arrow.cc b/python/pyarrow/src/arrow/python/python_to_arrow.cc index 2bb6a6f45955..7c0ffa70c7c0 100644 --- a/python/pyarrow/src/arrow/python/python_to_arrow.cc +++ b/python/pyarrow/src/arrow/python/python_to_arrow.cc @@ -762,7 +762,7 @@ class PyListConverter : public ListConverter { 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) { // Branch to support Python Dict with `map` DataType. auto items = PyDict_Items(value); OwnedRef item_ref(items); diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index e6de3113dee0..43b7704a885a 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -2144,7 +2144,7 @@ def test_to_list_of_maps_pandas(self): offsets = pa.array([0, 2, 5, 6], pa.int32()) keys = pa.array(['foo', 'bar', 'baz', 'qux', 'quux', 'quz']) items = pa.array([['a', 'b'], ['c', 'd'], [], None, [None, 'e'], ['f', 'g']], - pa.list_(pa.string())) + pa.list_(pa.string())) maps = pa.MapArray.from_arrays(offsets, keys, items) data = pa.ListArray.from_arrays([0, 1, 3], maps) @@ -4579,20 +4579,22 @@ def test_does_not_mutate_timedelta_nested(): def test_roundtrip_nested_map_table_with_pydicts(): - schema = pa.schema([pa.field("a", pa.list_(pa.map_(pa.int8(), pa.struct([pa.field("b", pa.binary())]))))]) + schema = pa.schema( + [pa.field("a", pa.list_(pa.map_(pa.int8(), pa.struct([pa.field("b", pa.binary())]))))]) table = pa.table([[ - [[(1, None)]], - None, - [ - [(2, {"b": b"abc"})], - [(3, {"b": None}), (4, {"b": b"def"})], - ] - ]], + [[(1, None)]], + None, + [ + [(2, {"b": b"abc"})], + [(3, {"b": None}), (4, {"b": b"def"})], + ] + ]], schema=schema, ) expected_default_df = pd.DataFrame( - {"a": [[[(1, None)]], None, [[(2, {"b": b"abc"})], [(3, {"b": None}), (4, {"b": b"def"})]]]} + {"a": [[[(1, None)]], None, [[(2, {"b": b"abc"})], + [(3, {"b": None}), (4, {"b": b"def"})]]]} ) expected_as_pydicts_df = pd.DataFrame( {"a": [[{1: None}], None, [{2: {"b": b"abc"}}, {3: {"b": None}, 4: {"b": b"def"}}]]} @@ -4607,5 +4609,5 @@ def test_roundtrip_nested_map_table_with_pydicts(): table_default_roundtrip = pa.Table.from_pandas(default_df, schema=schema) assert table.equals(table_default_roundtrip) - with pytest.raises(pa.ArrowTypeError): - table_as_pydicts_roundtrip = pa.Table.from_pandas(as_pydicts_df, schema=schema) \ No newline at end of file + table_as_pydicts_roundtrip = pa.Table.from_pandas(as_pydicts_df, schema=schema) + assert table.equals(table_as_pydicts_roundtrip) From 20a2cb0fd4bd57cb37d2f12e07fce1a5d7019e9d Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Fri, 14 Apr 2023 12:10:33 -0400 Subject: [PATCH 05/14] Fix python lint errors --- python/pyarrow/tests/test_pandas.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 43b7704a885a..02223ddb6b0c 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -4579,8 +4579,14 @@ def test_does_not_mutate_timedelta_nested(): def test_roundtrip_nested_map_table_with_pydicts(): - schema = pa.schema( - [pa.field("a", pa.list_(pa.map_(pa.int8(), pa.struct([pa.field("b", pa.binary())]))))]) + schema = pa.schema([ + pa.field( + "a", + pa.list_( + pa.map_(pa.int8(), pa.struct([pa.field("b", pa.binary())])) + ) + ) + ]) table = pa.table([[ [[(1, None)]], None, @@ -4597,7 +4603,11 @@ def test_roundtrip_nested_map_table_with_pydicts(): [(3, {"b": None}), (4, {"b": b"def"})]]]} ) expected_as_pydicts_df = pd.DataFrame( - {"a": [[{1: None}], None, [{2: {"b": b"abc"}}, {3: {"b": None}, 4: {"b": b"def"}}]]} + {"a": [ + [{1: None}], + None, + [{2: {"b": b"abc"}}, {3: {"b": None}, 4: {"b": b"def"}}], + ]} ) default_df = table.to_pandas() From 53cdb4acb456ee086221e0fde07b31a1e8924920 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Fri, 14 Apr 2023 19:48:40 -0400 Subject: [PATCH 06/14] Add additional tests for chunks and slices with list of maps --- python/pyarrow/tests/test_pandas.py | 190 ++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 02223ddb6b0c..1c47f887680d 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -2162,6 +2162,64 @@ def test_to_list_of_maps_pandas(self): DeprecationWarning) tm.assert_series_equal(series, expected) + def test_to_list_of_maps_pandas_sliced(self): + """ + A slightly more rigorous test for chunk/slice combinations + """ + + if ((Version(np.__version__) >= Version("1.25.0.dev0")) and + (Version(pd.__version__) < Version("2.0.0"))): + # TODO: regression in pandas with numpy 1.25dev + # https://github.com/pandas-dev/pandas/issues/50360 + pytest.skip("Regression in pandas with numpy 1.25") + + keys_1 = pa.array(['foo', 'bar']) + keys_2 = pa.array(['baz', 'qux', 'quux']) + keys_3 = pa.array(['quz']) + + items_1 = pa.array( + [['a', 'b'], ['c', 'd']], + pa.list_(pa.string()), + ) + items_2 = pa.array( + [[], None, [None, 'e']], + pa.list_(pa.string()), + ) + items_3 = pa.array( + [['f', 'g']], + pa.list_(pa.string()), + ) + + map_chunk_1 = pa.MapArray.from_arrays([0, 2], keys_1, items_1) + map_chunk_2 = pa.MapArray.from_arrays([0, 3], keys_2, items_2) + map_chunk_3 = pa.MapArray.from_arrays([0, 1], keys_3, items_3) + data = pa.chunked_array([ + pa.ListArray.from_arrays([0, 1], map_chunk_1), + pa.ListArray.from_arrays([0, 1], map_chunk_2), + pa.ListArray.from_arrays([0, 1], map_chunk_3), + ]) + + series = data.to_pandas() + expected = pd.Series([ + [[('foo', ['a', 'b']), ('bar', ['c', 'd'])]], + [[('baz', []), ('qux', None), ('quux', [None, 'e'])]], + [[('quz', ['f', 'g'])]], + ]) + + series_sliced = data.slice(1, 3).to_pandas() + expected_sliced = pd.Series([ + [[('baz', []), ('qux', None), ('quux', [None, 'e'])]], + [[('quz', ['f', 'g'])]], + ]) + + # pandas.testing generates a + # DeprecationWarning: elementwise comparison failed + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "elementwise comparison failed", + DeprecationWarning) + tm.assert_series_equal(series, expected) + tm.assert_series_equal(series_sliced, expected_sliced) + @pytest.mark.parametrize('t,data,expected', [ ( pa.int64, @@ -4621,3 +4679,135 @@ def test_roundtrip_nested_map_table_with_pydicts(): table_as_pydicts_roundtrip = pa.Table.from_pandas(as_pydicts_df, schema=schema) assert table.equals(table_as_pydicts_roundtrip) + + +def test_roundtrip_nested_map_array_with_pydicts_sliced(): + """ + Slightly more robust test with chunking and slicing + """ + keys_1 = pa.array(['foo', 'bar']) + keys_2 = pa.array(['baz', 'qux', 'quux', 'quz']) + keys_3 = pa.array([], pa.string()) + + items_1 = pa.array( + [['a', 'b'], ['c', 'd']], + pa.list_(pa.string()), + ) + items_2 = pa.array( + [[], None, [None, 'e'], ['f', 'g']], + pa.list_(pa.string()), + ) + items_3 = pa.array( + [], + pa.list_(pa.string()), + ) + + map_chunk_1 = pa.MapArray.from_arrays([0, 2], keys_1, items_1) + map_chunk_2 = pa.MapArray.from_arrays([0, 3, 4], keys_2, items_2) + map_chunk_3 = pa.MapArray.from_arrays([0, 0], keys_3, items_3) + chunked_array = pa.chunked_array([ + pa.ListArray.from_arrays([0, 1], map_chunk_1).slice(0), + pa.ListArray.from_arrays([0, 1], map_chunk_2.slice(1)).slice(0), + pa.ListArray.from_arrays([0, 0], map_chunk_3).slice(0), + ]) + + series_default = chunked_array.to_pandas() + expected_series_default = pd.Series([ + [[('foo', ['a', 'b']), ('bar', ['c', 'd'])]], + [[('quz', ['f', 'g'])]], + [], + ]) + + series_pydicts = chunked_array.to_pandas(maps_as_pydicts=True) + expected_series_pydicts = pd.Series([ + [{'foo': ['a', 'b'], 'bar': ['c', 'd']}], + [{'quz': ['f', 'g']}], + [], + ]) + + sliced = chunked_array.slice(1, 3) + series_default_sliced = sliced.to_pandas() + expected_series_default_sliced = pd.Series([ + [[('quz', ['f', 'g'])]], + [], + ]) + + series_pydicts_sliced = sliced.to_pandas(maps_as_pydicts=True) + expected_series_pydicts_sliced = pd.Series([ + [{'quz': ['f', 'g']}], + [], + ]) + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "elementwise comparison failed", + DeprecationWarning) + tm.assert_series_equal(series_default, expected_series_default) + tm.assert_series_equal(series_pydicts, expected_series_pydicts) + tm.assert_series_equal(series_default_sliced, expected_series_default_sliced) + tm.assert_series_equal(series_pydicts_sliced, expected_series_pydicts_sliced) + + ty = pa.list_(pa.map_(pa.string(), pa.list_(pa.string()))) + + def assert_roundtrip(series: pd.Series, data) -> None: + array_roundtrip = pa.chunked_array(pa.Array.from_pandas(series, type=ty)) + assert data.equals(array_roundtrip) + + assert_roundtrip(series_default, chunked_array) + assert_roundtrip(series_pydicts, chunked_array) + assert_roundtrip(series_default_sliced, sliced) + assert_roundtrip(series_pydicts_sliced, sliced) + + +def test_roundtrip_map_array_with_pydicts_duplicate_keys(): + keys = pa.array(['foo', 'bar', 'foo']) + items = pa.array( + [['a', 'b'], ['c', 'd'], ['1', '2']], + pa.list_(pa.string()), + ) + offsets = [0, 3] + maps = pa.MapArray.from_arrays(offsets, keys, items) + ty = pa.map_(pa.string(), pa.list_(pa.string())) + + # ------------------------ + # With maps as pydicts + series_pydicts = maps.to_pandas(maps_as_pydicts=True) + # some data loss occurs for duplicate keys + expected_series_pydicts = pd.Series([ + {'foo': ['1', '2'], 'bar': ['c', 'd']}, + ]) + tm.assert_series_equal(series_pydicts, expected_series_pydicts) + # roundtrip is not possible because of data loss + assert not maps.equals(pa.Array.from_pandas(series_pydicts, type=ty)) + + # ------------------------ + # With default assoc list of tuples + series_default = maps.to_pandas() + expected_series_default = pd.Series([ + [('foo', ['a', 'b']), ('bar', ['c', 'd']), ('foo', ['1', '2'])], + ]) + tm.assert_series_equal(series_default, expected_series_default) + assert maps.equals(pa.Array.from_pandas(series_default, type=ty)) + + +def test_unhashable_map_keys_with_pydicts(): + keys = pa.array( + [['a', 'b'], ['c', 'd'], [], ['e'], [None, 'f'], ['g', 'h']], + pa.list_(pa.string()), + ) + items = pa.array(['foo', 'bar', 'baz', 'qux', 'quux', 'quz']) + offsets = [0, 2, 6] + maps = pa.MapArray.from_arrays(offsets, keys, items) + + # ------------------------ + # With maps as pydicts + with pytest.raises(TypeError): + maps.to_pandas(maps_as_pydicts=True) + + # ------------------------ + # With default assoc list of tuples + series = maps.to_pandas() + expected_series_default = pd.Series([ + [(['a', 'b'], 'foo'), (['c', 'd'], 'bar')], + [([], 'baz'), (['e'], 'qux'), ([None, 'f'], 'quux'), (['g', 'h'], 'quz')], + ]) + tm.assert_series_equal(series, expected_series_default) From d7c776472eeb02c5a56b9b8c1051a315ac631147 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sat, 15 Apr 2023 10:26:49 -0400 Subject: [PATCH 07/14] Add custom error message for TypeError in new ConvertMap path --- .../src/arrow/python/arrow_to_pandas.cc | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index d52a40f0a1d8..d856a9962934 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -877,6 +877,31 @@ Status ConvertMapHelper( return Status::OK(); } +// A more helpful error message around TypeErrors that may stem from unhashable keys +Status CheckMapAsPydictsError() { + 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 `maps_as_pydicts=False`"; + + // resets the error + PyErr_SetString(PyExc_TypeError, message.c_str()); + } + return ConvertPyError(); +} + Status ConvertMap(PandasOptions options, const ChunkedArray& data, PyObject** out_values) { // Get columns of underlying key/item arrays @@ -951,7 +976,7 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, [&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()); - RETURN_IF_PYERROR(); + ARROW_RETURN_NOT_OK(CheckMapAsPydictsError()); // returns -1 if there are internal errors around hashing/resizing return setitem_result == 0 ? Status::OK() : From 58e7ddc3ad342ceebd6a26dd65c95ade7fc53682 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sat, 15 Apr 2023 12:11:49 -0400 Subject: [PATCH 08/14] Add detection and warning for duplicate keys with new pydict ConvertMap path --- .../src/arrow/python/arrow_to_pandas.cc | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index d856a9962934..5daa7c16875d 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -968,8 +968,12 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, } else { // Use a native pydict OwnedRef dict_item; - return ConvertMapHelper( - [&dict_item]([[maybe_unused]] int64_t) { + Py_ssize_t total_dict_len{0}; + Py_ssize_t total_raw_len{0}; + + auto status = ConvertMapHelper( + [&dict_item, &total_raw_len](int64_t num_pairs) { + total_raw_len += num_pairs; dict_item.reset(PyDict_New()); return CheckPyError(); }, @@ -984,12 +988,26 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, "Unexpected failure inserting Arrow (key, value) pair into Python dict" ); }, - [&dict_item]{ return dict_item.detach(); }, + [&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); + + if (status.ok() && (total_dict_len < total_raw_len)) { + const char* message = "After conversion of Arrow map to pydict, " + "detected possible data loss due to duplicate keys. " + "Input length is [%lld], total pydict length is [%lld]."; + std::array buf; + std::snprintf(buf.data(), buf.size(), message, total_raw_len, total_dict_len); + ARROW_LOG(WARNING) << buf.data(); + } + + return status; } } From 092793aeb96960b0810d1477aa25e219934affa0 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Sat, 15 Apr 2023 15:43:48 -0400 Subject: [PATCH 09/14] Add custom pd.Series comparison for compat w/ array_equivalent Pandas 1.0.0 has a different implementation of `array_equivalent` that raises errors, where newer versions of Pandas do not. So, we just due a somewhat clunky, yet functionally correct comparison between the series. --- python/pyarrow/tests/test_pandas.py | 33 ++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 1c47f887680d..30d668c8bef9 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -4775,7 +4775,6 @@ def test_roundtrip_map_array_with_pydicts_duplicate_keys(): expected_series_pydicts = pd.Series([ {'foo': ['1', '2'], 'bar': ['c', 'd']}, ]) - tm.assert_series_equal(series_pydicts, expected_series_pydicts) # roundtrip is not possible because of data loss assert not maps.equals(pa.Array.from_pandas(series_pydicts, type=ty)) @@ -4785,9 +4784,28 @@ def test_roundtrip_map_array_with_pydicts_duplicate_keys(): expected_series_default = pd.Series([ [('foo', ['a', 'b']), ('bar', ['c', 'd']), ('foo', ['1', '2'])], ]) - tm.assert_series_equal(series_default, expected_series_default) assert maps.equals(pa.Array.from_pandas(series_default, type=ty)) + # custom comparison for compatibility w/ Pandas 1.0.0 + # would otherwise run: + # tm.assert_series_equal(series_pydicts, expected_series_pydicts) + assert len(series_pydicts) == len(expected_series_pydicts) + for row1, row2 in zip(series_pydicts, expected_series_pydicts): + assert len(row1) == len(row2) + for tup1, tup2 in zip(row1.items(), row2.items()): + assert tup1[0] == tup2[0] + assert np.array_equal(tup1[1], tup2[1]) + + # custom comparison for compatibility w/ Pandas 1.0.0 + # would otherwise run: + # tm.assert_series_equal(series_default, expected_series_default) + assert len(series_default) == len(expected_series_default) + for row1, row2 in zip(series_default, expected_series_default): + assert len(row1) == len(row2) + for tup1, tup2 in zip(row1, row2): + assert tup1[0] == tup2[0] + assert np.array_equal(tup1[1], tup2[1]) + def test_unhashable_map_keys_with_pydicts(): keys = pa.array( @@ -4810,4 +4828,13 @@ def test_unhashable_map_keys_with_pydicts(): [(['a', 'b'], 'foo'), (['c', 'd'], 'bar')], [([], 'baz'), (['e'], 'qux'), ([None, 'f'], 'quux'), (['g', 'h'], 'quz')], ]) - tm.assert_series_equal(series, expected_series_default) + + # custom comparison for compatibility w/ Pandas 1.0.0 + # would otherwise run: + # tm.assert_series_equal(series, expected_series_default) + assert len(series) == len(expected_series_default) + for row1, row2 in zip(series, expected_series_default): + assert len(row1) == len(row2) + for tup1, tup2 in zip(row1, row2): + assert np.array_equal(tup1[0], tup2[0]) + assert tup1[1] == tup2[1] From f0dd00a368b119f65336b1fbe85522b1e4cd6680 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Mon, 17 Apr 2023 00:49:58 -0400 Subject: [PATCH 10/14] Iteration upon error messages --- python/pyarrow/src/arrow/python/arrow_to_pandas.cc | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index 5daa7c16875d..c8f2c6620b46 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -894,7 +894,8 @@ Status CheckMapAsPydictsError() { 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 `maps_as_pydicts=False`"; + message += ". If keys are not hashable, then you must use the option " + "[maps_as_pydicts=False (default)]"; // resets the error PyErr_SetString(PyExc_TypeError, message.c_str()); @@ -984,7 +985,7 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, // returns -1 if there are internal errors around hashing/resizing return setitem_result == 0 ? Status::OK() : - Status::UnknownError( + Status::UnknownError("[maps_as_pydicts=True] " "Unexpected failure inserting Arrow (key, value) pair into Python dict" ); }, @@ -999,9 +1000,10 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, out_values); if (status.ok() && (total_dict_len < total_raw_len)) { - const char* message = "After conversion of Arrow map to pydict, " - "detected possible data loss due to duplicate keys. " - "Input length is [%lld], total pydict length is [%lld]."; + const char* message = "[maps_as_pydicts=True] " + "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 buf; std::snprintf(buf.data(), buf.size(), message, total_raw_len, total_dict_len); ARROW_LOG(WARNING) << buf.data(); From 551990bc96a728ddb17d5d8517ede2c83e1a1c4f Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Tue, 18 Apr 2023 21:13:51 -0400 Subject: [PATCH 11/14] Add `lossy` or `strict` option to `maps_as_pydicts` --- python/pyarrow/array.pxi | 33 ++++++++--- python/pyarrow/includes/libarrow_python.pxd | 9 ++- .../src/arrow/python/arrow_to_pandas.cc | 57 +++++++++++++------ .../src/arrow/python/arrow_to_pandas.h | 19 +++++-- python/pyarrow/tests/test_pandas.py | 13 +++-- 5 files changed, 96 insertions(+), 35 deletions(-) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index 29cf8a3c6248..79a45746bfd6 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -699,7 +699,7 @@ cdef class _PandasConvertible(_Weakrefable): bint safe=True, bint split_blocks=False, bint self_destruct=False, - bint maps_as_pydicts=False, + str maps_as_pydicts=None, types_mapper=None ): """ @@ -754,13 +754,19 @@ cdef class _PandasConvertible(_Weakrefable): Note that you may not see always memory usage improvements. For example, if multiple columns share an underlying allocation, memory can't be freed until all columns are converted. - maps_as_pydicts : bool, default False - If true, convert Arrow Map arrays to native Python dicts. + maps_as_pydicts : str, optional, default `None` + Valid values are `None`, 'lossy', or 'strict'. + The default behavior (`None`), is to convert Arrow Map arrays to + Python association lists (list-of-tuples) in the same order as the + Arrow Map, as in [(key1, value1), (key2, value2), ...]. + + If 'lossy' or 'strict', convert Arrow Map arrays to native Python dicts. This can change the ordering of (key, value) pairs, and will deduplicate multiple keys, resulting in a possible loss of data. - The default behavior (false), is to convert Arrow Map arrays to - Python list-of-tuples in the same order as the Arrow Map, as in - [(key1, value1), (key2, value2), ...] + + If 'lossy', this key deduplication results in a warning printed + when detected. If 'strict', this instead results in an exception + being raised when detected. types_mapper : function, default None A function mapping a pyarrow DataType to a pandas ExtensionDtype. This can be used to override the default pandas type for conversion @@ -862,7 +868,20 @@ cdef PandasOptions _convert_pandas_options(dict options): result.split_blocks = options['split_blocks'] result.self_destruct = options['self_destruct'] result.ignore_timezone = os.environ.get('PYARROW_IGNORE_TIMEZONE', False) - result.maps_as_pydicts = options['maps_as_pydicts'] + + maps_as_pydicts = options['maps_as_pydicts'] + if maps_as_pydicts is None: + result.maps_as_pydicts = MapConversionType.DEFAULT + elif maps_as_pydicts == "lossy": + result.maps_as_pydicts = MapConversionType.LOSSY + elif maps_as_pydicts == "strict": + result.maps_as_pydicts = MapConversionType.STRICT + else: + raise ValueError( + "Invalid value for 'maps_as_pydicts': " + + "valid values are 'lossy', 'strict' or `None` (default). " + + f"Received '{maps_as_pydicts}'." + ) return result diff --git a/python/pyarrow/includes/libarrow_python.pxd b/python/pyarrow/includes/libarrow_python.pxd index 7999f0a493ec..60adff37271f 100644 --- a/python/pyarrow/includes/libarrow_python.pxd +++ b/python/pyarrow/includes/libarrow_python.pxd @@ -45,6 +45,13 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py::internal": const CMonthDayNanoIntervalScalar& scalar) +cdef extern from "arrow/python/arrow_to_pandas.h" namespace "arrow::py::MapConversionType": + cdef enum MapConversionType "arrow::py::MapConversionType": + DEFAULT, + LOSSY, + STRICT + + cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: shared_ptr[CDataType] GetPrimitiveType(Type type) @@ -186,7 +193,7 @@ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: c_bool safe_cast c_bool split_blocks c_bool self_destruct - c_bool maps_as_pydicts + MapConversionType maps_as_pydicts c_bool decode_dictionaries unordered_set[c_string] categorical_columns unordered_set[c_string] extension_columns diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index c8f2c6620b46..fdb820e7b24b 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -878,11 +878,10 @@ Status ConvertMapHelper( } // A more helpful error message around TypeErrors that may stem from unhashable keys -Status CheckMapAsPydictsError() { +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. @@ -895,7 +894,7 @@ Status CheckMapAsPydictsError() { 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=False (default)]"; + "[maps_as_pydicts=None (default)]"; // resets the error PyErr_SetString(PyExc_TypeError, message.c_str()); @@ -903,6 +902,26 @@ Status CheckMapAsPydictsError() { 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 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 @@ -947,7 +966,7 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, PyArrayObject* py_keys = reinterpret_cast(owned_numpy_keys.obj()); PyArrayObject* py_items = reinterpret_cast(owned_numpy_items.obj()); - if (!options.maps_as_pydicts) { + 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( @@ -972,6 +991,18 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, 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(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; @@ -981,11 +1012,11 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, [&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(CheckMapAsPydictsError()); + 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=True] " + Status::UnknownError("[maps_as_pydicts] " "Unexpected failure inserting Arrow (key, value) pair into Python dict" ); }, @@ -999,17 +1030,9 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, item_arrays, out_values); - if (status.ok() && (total_dict_len < total_raw_len)) { - const char* message = "[maps_as_pydicts=True] " - "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 buf; - std::snprintf(buf.data(), buf.size(), message, total_raw_len, total_dict_len); - ARROW_LOG(WARNING) << buf.data(); - } - - return status; + // If there were no errors generating the pydicts, + // then check if we detected any data loss from duplicate keys. + return !status.ok() ? status : CheckForDuplicateKeys(error_on_duplicate_keys, total_dict_len, total_raw_len); } } diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.h b/python/pyarrow/src/arrow/python/arrow_to_pandas.h index 20e8ee6504df..bfcc6f9abdb7 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.h +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.h @@ -41,6 +41,12 @@ class Table; namespace py { +enum class MapConversionType { + DEFAULT, // convert arrow maps to assoc lists (list of kev-value tuples) in Pandas + LOSSY, // report warnings when lossiness is encountered due to duplicate keys + STRICT, // raise a Python exception when lossiness is encountered due to duplicate keys +}; + struct PandasOptions { /// arrow::MemoryPool to use for memory allocations MemoryPool* pool = default_memory_pool(); @@ -90,13 +96,16 @@ struct PandasOptions { /// conversions bool self_destruct = false; - /// \brief If true, convert Arrow Map arrays to native Python dicts. + /// \brief The default behavior (DEFAULT), is to convert Arrow Map arrays to + /// Python association lists (list-of-tuples) in the same order as the Arrow + /// Map, as in [(key1, value1), (key2, value2), ...] + /// If LOSSY or STRICT, convert Arrow Map arrays to native Python dicts. /// This can change the ordering of (key, value) pairs, and will deduplicate /// multiple keys, resulting in a possible loss of data. - /// The default behavior (false), is to convert Arrow Map arrays to Python - /// list-of-tuples in the same order as the Arrow Map, - /// as in [(key1, value1), (key2, value2), ...] - bool maps_as_pydicts = false; + /// If 'lossy', this key deduplication results in a warning printed + /// when detected. If 'strict', this instead results in an exception + /// being raised when detected. + MapConversionType maps_as_pydicts = MapConversionType::DEFAULT; // Used internally for nested arrays. bool decode_dictionaries = false; diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 30d668c8bef9..ddc5c5db3791 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -4669,7 +4669,7 @@ def test_roundtrip_nested_map_table_with_pydicts(): ) default_df = table.to_pandas() - as_pydicts_df = table.to_pandas(maps_as_pydicts=True) + as_pydicts_df = table.to_pandas(maps_as_pydicts="strict") tm.assert_frame_equal(default_df, expected_default_df) tm.assert_frame_equal(as_pydicts_df, expected_as_pydicts_df) @@ -4718,7 +4718,7 @@ def test_roundtrip_nested_map_array_with_pydicts_sliced(): [], ]) - series_pydicts = chunked_array.to_pandas(maps_as_pydicts=True) + series_pydicts = chunked_array.to_pandas(maps_as_pydicts="strict") expected_series_pydicts = pd.Series([ [{'foo': ['a', 'b'], 'bar': ['c', 'd']}], [{'quz': ['f', 'g']}], @@ -4732,7 +4732,7 @@ def test_roundtrip_nested_map_array_with_pydicts_sliced(): [], ]) - series_pydicts_sliced = sliced.to_pandas(maps_as_pydicts=True) + series_pydicts_sliced = sliced.to_pandas(maps_as_pydicts="strict") expected_series_pydicts_sliced = pd.Series([ [{'quz': ['f', 'g']}], [], @@ -4770,7 +4770,10 @@ def test_roundtrip_map_array_with_pydicts_duplicate_keys(): # ------------------------ # With maps as pydicts - series_pydicts = maps.to_pandas(maps_as_pydicts=True) + with pytest.raises(pa.lib.ArrowException): + # raises because of duplicate keys + maps.to_pandas(maps_as_pydicts="strict") + series_pydicts = maps.to_pandas(maps_as_pydicts="lossy") # some data loss occurs for duplicate keys expected_series_pydicts = pd.Series([ {'foo': ['1', '2'], 'bar': ['c', 'd']}, @@ -4819,7 +4822,7 @@ def test_unhashable_map_keys_with_pydicts(): # ------------------------ # With maps as pydicts with pytest.raises(TypeError): - maps.to_pandas(maps_as_pydicts=True) + maps.to_pandas(maps_as_pydicts="lossy") # ------------------------ # With default assoc list of tuples From 69ee841d13db8a09a66d620cd7750612e3cce38b Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Wed, 19 Apr 2023 08:48:03 -0400 Subject: [PATCH 12/14] Try to fix C2589 error I'm guessing this is due to a macro somewhere for STRICT --- python/pyarrow/array.pxi | 2 +- python/pyarrow/includes/libarrow_python.pxd | 2 +- python/pyarrow/src/arrow/python/arrow_to_pandas.cc | 2 +- python/pyarrow/src/arrow/python/arrow_to_pandas.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index 79a45746bfd6..542a3c19f3cd 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -875,7 +875,7 @@ cdef PandasOptions _convert_pandas_options(dict options): elif maps_as_pydicts == "lossy": result.maps_as_pydicts = MapConversionType.LOSSY elif maps_as_pydicts == "strict": - result.maps_as_pydicts = MapConversionType.STRICT + result.maps_as_pydicts = MapConversionType.STRICT_ else: raise ValueError( "Invalid value for 'maps_as_pydicts': " diff --git a/python/pyarrow/includes/libarrow_python.pxd b/python/pyarrow/includes/libarrow_python.pxd index 60adff37271f..2052600c9f3a 100644 --- a/python/pyarrow/includes/libarrow_python.pxd +++ b/python/pyarrow/includes/libarrow_python.pxd @@ -49,7 +49,7 @@ cdef extern from "arrow/python/arrow_to_pandas.h" namespace "arrow::py::MapConve cdef enum MapConversionType "arrow::py::MapConversionType": DEFAULT, LOSSY, - STRICT + STRICT_ cdef extern from "arrow/python/api.h" namespace "arrow::py" nogil: diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index fdb820e7b24b..516618c0a113 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -994,7 +994,7 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, 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) { + } else if (options.maps_as_pydicts == MapConversionType::STRICT_) { error_on_duplicate_keys = true; } else { auto val = std::underlying_type_t(options.maps_as_pydicts); diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.h b/python/pyarrow/src/arrow/python/arrow_to_pandas.h index bfcc6f9abdb7..ac422cc99c67 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.h +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.h @@ -44,7 +44,7 @@ namespace py { enum class MapConversionType { DEFAULT, // convert arrow maps to assoc lists (list of kev-value tuples) in Pandas LOSSY, // report warnings when lossiness is encountered due to duplicate keys - STRICT, // raise a Python exception when lossiness is encountered due to duplicate keys + STRICT_, // raise a Python exception when lossiness is encountered due to duplicate keys }; struct PandasOptions { From ddd67646c4f895910a14f3d6612a9515269a8924 Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Wed, 19 Apr 2023 16:33:05 -0400 Subject: [PATCH 13/14] Use ARROW_RETURN_NOT_OK convention --- python/pyarrow/src/arrow/python/arrow_to_pandas.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc index 516618c0a113..32a97ac7562c 100644 --- a/python/pyarrow/src/arrow/python/arrow_to_pandas.cc +++ b/python/pyarrow/src/arrow/python/arrow_to_pandas.cc @@ -1030,9 +1030,10 @@ Status ConvertMap(PandasOptions options, const ChunkedArray& data, 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 !status.ok() ? status : CheckForDuplicateKeys(error_on_duplicate_keys, total_dict_len, total_raw_len); + return CheckForDuplicateKeys(error_on_duplicate_keys, total_dict_len, total_raw_len); } } From 9e1dec003b3d2fd62d6b16af26f58e13856d6dea Mon Sep 17 00:00:00 2001 From: Mike Lui Date: Wed, 19 Apr 2023 16:50:08 -0400 Subject: [PATCH 14/14] Simplify overly complex tests --- python/pyarrow/tests/test_pandas.py | 57 ++++++++--------------------- 1 file changed, 16 insertions(+), 41 deletions(-) diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index ddc5c5db3791..803a41c28a7a 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -2141,19 +2141,13 @@ def test_to_list_of_maps_pandas(self): # TODO: regression in pandas with numpy 1.25dev # https://github.com/pandas-dev/pandas/issues/50360 pytest.skip("Regression in pandas with numpy 1.25") - offsets = pa.array([0, 2, 5, 6], pa.int32()) - keys = pa.array(['foo', 'bar', 'baz', 'qux', 'quux', 'quz']) - items = pa.array([['a', 'b'], ['c', 'd'], [], None, [None, 'e'], ['f', 'g']], - pa.list_(pa.string())) - maps = pa.MapArray.from_arrays(offsets, keys, items) - data = pa.ListArray.from_arrays([0, 1, 3], maps) - - expected = pd.Series([ + data = [ [[('foo', ['a', 'b']), ('bar', ['c', 'd'])]], [[('baz', []), ('qux', None), ('quux', [None, 'e'])], [('quz', ['f', 'g'])]] - ]) - - series = pd.Series(data.to_pandas()) + ] + arr = pa.array(data, pa.list_(pa.map_(pa.utf8(), pa.list_(pa.utf8())))) + series = arr.to_pandas() + expected = pd.Series(data) # pandas.testing generates a # DeprecationWarning: elementwise comparison failed @@ -2173,43 +2167,24 @@ def test_to_list_of_maps_pandas_sliced(self): # https://github.com/pandas-dev/pandas/issues/50360 pytest.skip("Regression in pandas with numpy 1.25") - keys_1 = pa.array(['foo', 'bar']) - keys_2 = pa.array(['baz', 'qux', 'quux']) - keys_3 = pa.array(['quz']) - - items_1 = pa.array( - [['a', 'b'], ['c', 'd']], + keys = pa.array(['ignore', 'foo', 'bar', 'baz', + 'qux', 'quux', 'ignore']).slice(1, 5) + items = pa.array( + [['ignore'], ['ignore'], ['a', 'b'], ['c', 'd'], [], None, [None, 'e']], pa.list_(pa.string()), - ) - items_2 = pa.array( - [[], None, [None, 'e']], - pa.list_(pa.string()), - ) - items_3 = pa.array( - [['f', 'g']], - pa.list_(pa.string()), - ) - - map_chunk_1 = pa.MapArray.from_arrays([0, 2], keys_1, items_1) - map_chunk_2 = pa.MapArray.from_arrays([0, 3], keys_2, items_2) - map_chunk_3 = pa.MapArray.from_arrays([0, 1], keys_3, items_3) - data = pa.chunked_array([ - pa.ListArray.from_arrays([0, 1], map_chunk_1), - pa.ListArray.from_arrays([0, 1], map_chunk_2), - pa.ListArray.from_arrays([0, 1], map_chunk_3), - ]) + ).slice(2, 5) + map = pa.MapArray.from_arrays([0, 2, 4], keys, items) + arr = pa.ListArray.from_arrays([0, 1, 2], map) - series = data.to_pandas() + series = arr.to_pandas() expected = pd.Series([ [[('foo', ['a', 'b']), ('bar', ['c', 'd'])]], - [[('baz', []), ('qux', None), ('quux', [None, 'e'])]], - [[('quz', ['f', 'g'])]], + [[('baz', []), ('qux', None)]], ]) - series_sliced = data.slice(1, 3).to_pandas() + series_sliced = arr.slice(1, 2).to_pandas() expected_sliced = pd.Series([ - [[('baz', []), ('qux', None), ('quux', [None, 'e'])]], - [[('quz', ['f', 'g'])]], + [[('baz', []), ('qux', None)]], ]) # pandas.testing generates a