diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 1abe4235c411..926cce7175a2 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -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 ------- @@ -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( @@ -542,6 +542,8 @@ 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 @@ -549,14 +551,20 @@ cdef class ChunkedArray(_PandasConvertible): 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) if dtype is None: return values return values.astype(dtype, copy=False) diff --git a/python/pyarrow/tests/test_array.py b/python/pyarrow/tests/test_array.py index adc3e097b54a..1bd52566d54b 100644 --- a/python/pyarrow/tests/test_array.py +++ b/python/pyarrow/tests/test_array.py @@ -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) diff --git a/python/pyarrow/tests/test_table.py b/python/pyarrow/tests/test_table.py index cb010f4387b6..91d78b84cc4f 100644 --- a/python/pyarrow/tests/test_table.py +++ b/python/pyarrow/tests/test_table.py @@ -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 + + def test_chunked_array_mismatch_types(): msg = "chunks must all be same type" with pytest.raises(TypeError, match=msg):