From bd3b121fc484162d1407e9f39032b13294dca7cf Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Thu, 10 Dec 2020 14:11:03 +0100 Subject: [PATCH 1/2] ARROW-10863: [Python] Fix ExtensionArray.to_pandas to use underlying storage array --- python/pyarrow/array.pxi | 5 +-- python/pyarrow/tests/test_extension_type.py | 41 +++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index a6b3725e4899..118976e22937 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -2243,10 +2243,7 @@ cdef class ExtensionArray(Array): return result def _to_pandas(self, options, **kwargs): - result = Array._to_pandas(self, options, **kwargs) - # TODO(wesm): is passing through these parameters to the storage array - # correct? - return result.to_pandas(options, **kwargs) + return Array._to_pandas(self.storage, options, **kwargs) def to_numpy(self, **kwargs): """ diff --git a/python/pyarrow/tests/test_extension_type.py b/python/pyarrow/tests/test_extension_type.py index 1ef70e79696f..8e9cb1a9300e 100644 --- a/python/pyarrow/tests/test_extension_type.py +++ b/python/pyarrow/tests/test_extension_type.py @@ -209,6 +209,47 @@ def test_ext_array_pickling(): assert arr.storage.to_pylist() == [b"foo", b"bar"] +def test_ext_array_conversion_to_numpy(): + storage1 = pa.array([1, 2, 3], type=pa.int64()) + storage2 = pa.array([b"123", b"456", b"789"], type=pa.binary(3)) + ty1 = IntegerType() + ty2 = ParamExtType(3) + + arr1 = pa.ExtensionArray.from_storage(ty1, storage1) + arr2 = pa.ExtensionArray.from_storage(ty2, storage2) + + result = arr1.to_numpy() + expected = np.array([1, 2, 3], dtype="int64") + np.testing.assert_array_equal(result, expected) + + with pytest.raises(ValueError, match="zero_copy_only was True"): + arr2.to_numpy() + result = arr2.to_numpy(zero_copy_only=False) + expected = np.array([b"123", b"456", b"789"]) + np.testing.assert_array_equal(result, expected) + + +@pytest.mark.pandas +def test_ext_array_conversion_to_pandas(): + import pandas as pd + + storage1 = pa.array([1, 2, 3], type=pa.int64()) + storage2 = pa.array([b"123", b"456", b"789"], type=pa.binary(3)) + ty1 = IntegerType() + ty2 = ParamExtType(3) + + arr1 = pa.ExtensionArray.from_storage(ty1, storage1) + arr2 = pa.ExtensionArray.from_storage(ty2, storage2) + + result = arr1.to_pandas() + expected = pd.Series([1, 2, 3], dtype="int64") + pd.testing.assert_series_equal(result, expected) + + result = arr2.to_pandas() + expected = pd.Series([b"123", b"456", b"789"], dtype=object) + pd.testing.assert_series_equal(result, expected) + + def test_cast_kernel_on_extension_arrays(): # test array casting storage = pa.array([1, 2, 3, 4], pa.int64()) From cded64c0921984d4332b5f7b1257c1e2a740771b Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Tue, 15 Dec 2020 15:47:50 +0100 Subject: [PATCH 2/2] support full roundtrip in Array.to_pandas for pandas ExtensionDtypes --- python/pyarrow/array.pxi | 12 ++++++++++++ python/pyarrow/tests/test_pandas.py | 26 ++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index 118976e22937..ae9e213b98dd 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -2243,6 +2243,18 @@ cdef class ExtensionArray(Array): return result def _to_pandas(self, options, **kwargs): + pandas_dtype = None + try: + pandas_dtype = self.type.to_pandas_dtype() + except NotImplementedError: + pass + + # pandas ExtensionDtype that implements conversion from pyarrow + if hasattr(pandas_dtype, '__from_arrow__'): + arr = pandas_dtype.__from_arrow__(self) + return pandas_api.series(arr) + + # otherwise convert the storage array with the base implementation return Array._to_pandas(self.storage, options, **kwargs) def to_numpy(self, **kwargs): diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 06711210f9af..4526baddb7a0 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -3955,6 +3955,11 @@ def test_conversion_extensiontype_to_extensionarray(monkeypatch): # extension type points to Int64Dtype, which knows how to create a # pandas ExtensionArray + result = arr.to_pandas() + assert isinstance(result._data.blocks[0], _int.ExtensionBlock) + expected = pd.Series([1, 2, 3, 4], dtype='Int64') + tm.assert_series_equal(result, expected) + result = table.to_pandas() assert isinstance(result._data.blocks[0], _int.ExtensionBlock) expected = pd.DataFrame({'a': pd.array([1, 2, 3, 4], dtype='Int64')}) @@ -3969,6 +3974,11 @@ def test_conversion_extensiontype_to_extensionarray(monkeypatch): pd.core.arrays.integer._IntegerDtype, "__from_arrow__", raising=False) + result = arr.to_pandas() + assert not isinstance(result._data.blocks[0], _int.ExtensionBlock) + expected = pd.Series([1, 2, 3, 4]) + tm.assert_series_equal(result, expected) + with pytest.raises(ValueError): table.to_pandas() @@ -4001,6 +4011,22 @@ def test_to_pandas_extension_dtypes_mapping(): assert isinstance(result['a'].dtype, pd.PeriodDtype) +def test_array_to_pandas(): + if LooseVersion(pd.__version__) < "1.0": + pytest.skip("ExtensionDtype __from_arrow__ protocol missing") + + for arr in [pd.period_range("2012-01-01", periods=3, freq="D").array, + pd.interval_range(1, 4).array]: + result = pa.array(arr).to_pandas() + expected = pd.Series(arr) + tm.assert_series_equal(result, expected) + + # TODO implement proper conversion for chunked array + # result = pa.table({"col": arr})["col"].to_pandas() + # expected = pd.Series(arr, name="col") + # tm.assert_series_equal(result, expected) + + # ---------------------------------------------------------------------- # Legacy metadata compatibility tests