Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions python/pyarrow/array.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -2243,10 +2243,19 @@ 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)
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):
"""
Expand Down
41 changes: 41 additions & 0 deletions python/pyarrow/tests/test_extension_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
26 changes: 26 additions & 0 deletions python/pyarrow/tests/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')})
Expand All @@ -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()

Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is failed on wheel-manylinux*-cp{36,37}*:

https://dev.azure.com/ursa-labs/crossbow/_build/results?buildId=21715&view=logs&j=0da5d1d9-276d-5173-c4c4-9d4d4ed14fdb&t=3367cfe7-6aa5-5a88-c888-e6814d74f6eb&l=176

    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)
E           AssertionError: Attributes of Series are different
E           
E           Attribute "dtype" are different
E           [left]:  int64
E           [right]: period[D]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, maybe my skip for pandas was wrong. Is there any way to see which pandas version is being used in that wheel build? (based on the requirements-wheel-test.txt file I would assume the latest, but I don't see it anywhere in the output)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In any case, the feature was only added in pandas 1.1, not 1.0, so the skip I added was wrong. Fixing that in #8934



# ----------------------------------------------------------------------
# Legacy metadata compatibility tests

Expand Down