Skip to content
Open
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
36 changes: 22 additions & 14 deletions python/pyarrow/table.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -493,13 +493,16 @@ cdef class ChunkedArray(_PandasConvertible):

def to_numpy(self, zero_copy_only=False):
"""
Return a NumPy copy of this array (experimental).
Return a NumPy view or copy of this array.

A single chunk may be returned as a zero-copy, read-only view.
Multiple chunks or null values require a copy. This method does not
provide an option to force a copy.

Parameters
----------
zero_copy_only : bool, default False
Introduced for signature consistence with pyarrow.Array.to_numpy.
This must be False here since NumPy arrays' buffer must be contiguous.
If True, raise an exception when conversion requires copying data.

Returns
-------
Expand All @@ -516,16 +519,13 @@ cdef class ChunkedArray(_PandasConvertible):
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
if zero_copy_only:
raise ValueError(
"zero_copy_only must be False for pyarrow.ChunkedArray.to_numpy"
)
cdef:
PyObject* out
PandasOptions c_options
object values

c_options.to_numpy = True
c_options.zero_copy_only = zero_copy_only

with nogil:
check_status(
Expand All @@ -542,21 +542,29 @@ cdef class ChunkedArray(_PandasConvertible):
values = PyObject_to_object(out)

if isinstance(values, dict):
if zero_copy_only:
raise ArrowInvalid("Cannot decode a dictionary without copying")
values = np.take(values['dictionary'], values['indices'])

return values

def __array__(self, dtype=None, copy=None):
self._assert_cpu()
if copy is False:
raise ValueError(
"Unable to avoid a copy while creating a numpy array as requested "
"(converting a pyarrow.ChunkedArray always results in a copy).\n"
"If using `np.array(obj, copy=False)` replace it with "
"`np.asarray(obj)` to allow a copy when needed"
)
# 'copy' can further be ignored because to_numpy() already returns a copy
try:
values = self.to_numpy(zero_copy_only=True)
except ArrowInvalid:
raise ValueError(
"Unable to avoid a copy while creating a numpy array as requested.\n"
"If using `np.array(obj, copy=False)` replace it with "
"`np.asarray(obj)` to allow a copy when needed"
)
if dtype is not None and np.dtype(dtype) != values.dtype:
raise ValueError("Unable to avoid a copy while converting the dtype")
return values
values = self.to_numpy()
if copy is True and not values.flags.writeable:
return np.array(values, dtype=dtype, copy=True)
Comment thread
jingyi-zhao-01 marked this conversation as resolved.
Resolved
if dtype is None:
return values
return values.astype(dtype, copy=False)
Expand Down
2 changes: 1 addition & 1 deletion python/pyarrow/tests/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def test_chunked_array_to_numpy_zero_copy():

chunked_arr = pa.chunked_array(elements)

msg = "zero_copy_only must be False for pyarrow.ChunkedArray.to_numpy"
msg = "Needed to copy"

with pytest.raises(ValueError, match=msg):
chunked_arr.to_numpy(zero_copy_only=True)
Expand Down
95 changes: 95 additions & 0 deletions python/pyarrow/tests/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,101 @@ def test_chunked_array_to_numpy():
assert np.array_equal(arr1, arr2)


@pytest.mark.numpy
def test_chunked_array_numpy_zero_copy():
from pyarrow.vendored.version import Version

chunk = pa.array([1, 2, 3, 4]).slice(1, 2)
data = pa.chunked_array([chunk])
for result in (data.to_numpy(zero_copy_only=True),
data.__array__(copy=False),
data.__array__(dtype=np.dtype("int64"), copy=False)):
assert result.ctypes.data == chunk.buffers()[1].address + chunk.offset * 8
assert not result.flags.writeable
assert result.tolist() == [2, 3]
with pytest.raises(ValueError):
data.__array__(dtype=np.dtype("float64"), copy=False)
if Version(np.__version__) >= Version("2.0.0.dev0"):
assert np.array(data, copy=False).ctypes.data == result.ctypes.data
with pytest.raises(ValueError):
np.array(data, dtype="float64", copy=False)


@pytest.mark.numpy
@pytest.mark.parametrize("data", [
pa.chunked_array([], type=pa.int64()),
pa.chunked_array([[1], [2]]),
pa.chunked_array([[1, None]]),
pa.chunked_array([[True, False]]),
pa.chunked_array([pa.array([1, 2, 1]).dictionary_encode()]),
pa.chunked_array([pa.array(["a", "b"]).dictionary_encode()]),
pa.chunked_array([pc.run_end_encode(pa.array([1, 1, 2]))]),
])
def test_chunked_array_numpy_zero_copy_unavailable(data):
with pytest.raises(ValueError):
data.to_numpy(zero_copy_only=True)
with pytest.raises(ValueError, match="Unable to avoid a copy"):
data.__array__(copy=False)


@pytest.mark.numpy
def test_chunked_array_numpy_zero_copy_extension_storage():
class DictionaryExtensionType(pa.ExtensionType):
def __init__(self, storage_type):
super().__init__(storage_type, "test.numpy_dictionary")

def __arrow_ext_serialize__(self):
return b""

storage = pa.array([1, 2, 1]).dictionary_encode()
data = pa.chunked_array([pa.ExtensionArray.from_storage(
DictionaryExtensionType(storage.type), storage
)])
with pytest.raises(ValueError):
data.to_numpy(zero_copy_only=True)
with pytest.raises(ValueError):
data.__array__(copy=False)


@pytest.mark.numpy
def test_chunked_array_array_copy_true_is_writable():
data = pa.chunked_array([[1, 2, 3]])
result = data.__array__(copy=True)

assert result.flags.writeable
result[0] = 99
assert result.tolist() == [99, 2, 3]
assert data.to_pylist() == [1, 2, 3]

result = data.__array__(dtype=np.dtype("float64"), copy=True)
assert result.dtype == "float64"
assert result.flags.writeable


@pytest.mark.numpy
@pytest.mark.parametrize("chunks", [[[1, 2], [3]], [[1, None, 3]]])
@pytest.mark.parametrize("dtype", [None, "float64"])
def test_chunked_array_array_copy_true_avoids_extra_copy(chunks, dtype, monkeypatch):
data = pa.chunked_array(chunks)
original = data.to_pylist()
numpy_array = np.array

def no_extra_copy(*args, **kwargs):
raise AssertionError("unnecessary np.array copy")

with monkeypatch.context() as patch:
patch.setattr(np, "array", no_extra_copy)
result = data.__array__(dtype=dtype, copy=True)

expected = numpy_array(original, dtype=dtype or result.dtype)
np.testing.assert_equal(result, expected)
assert result.flags.writeable
if dtype is not None:
assert result.dtype == dtype
result[0] = 99
assert data.to_pylist() == original

Comment thread
jingyi-zhao-01 marked this conversation as resolved.
Resolved

def test_chunked_array_mismatch_types():
msg = "chunks must all be same type"
with pytest.raises(TypeError, match=msg):
Expand Down
Loading