diff --git a/docs/source/cpp/compute.rst b/docs/source/cpp/compute.rst index 4c2df6b3176..795c2e021d7 100644 --- a/docs/source/cpp/compute.rst +++ b/docs/source/cpp/compute.rst @@ -1984,27 +1984,31 @@ Structural transforms The output type is an Array of items for the ``FIRST``/``LAST`` options and an Array of List of items for the ``ALL`` option. -* \(6) Extract a child value based on a sequence of indices passed in - the options. The validity bitmap of the result will be the - intersection of all intermediate validity bitmaps. For example, for - an array with type ``struct>``: +* \(6) Extract a child value based on a field reference passed in the + options. The reference can be a sequence of child indices (a + :class:`FieldPath`), a child field name, or a nested sequence of + these (see :class:`FieldRef`; note that a dot path such as ``"b.d"`` + must first be parsed with ``FieldRef::FromDotPath``). The validity + bitmap of the result will be the intersection of all intermediate + validity bitmaps. For example, for an array with type + ``struct>``: * An empty sequence of indices yields the original value unchanged. - * The index ``0`` yields an array of type ``int32`` whose validity - bitmap is the intersection of the bitmap for the outermost struct - and the bitmap for the child ``a``. - * The index ``1, 1`` yields an array of type ``float64`` whose - validity bitmap is the intersection of the bitmaps for the - outermost struct, for struct ``b``, and for the child ``d``. + * The index ``0`` or the field name ``"a"`` yields an array of type + ``int32`` whose validity bitmap is the intersection of the bitmap + for the outermost struct and the bitmap for the child ``a``. + * The indices ``1, 1`` or the field names ``"b", "d"`` yield an + array of type ``float64`` whose validity bitmap is the + intersection of the bitmaps for the outermost struct, for struct + ``b``, and for the child ``d``. For unions, a validity bitmap is synthesized based on the type codes. Also, the index is always the child index and not a type code. Hence for array with type ``sparse_union<2: int32, 7: utf8>``: * The index ``0`` yields an array of type ``int32``, which is valid - at an index *n* if and only if the child array ``a`` is valid at - index *n* and the type code at index *n* is 2. + at an index *n* if and only if the child array of type ``int32`` + is valid at index *n* and the type code at index *n* is 2. * The indices ``2`` and ``7`` are invalid. * \(7) Output is true for each list containing a value equal to the second diff --git a/docs/source/python/parquet/parquet_datasets.rst b/docs/source/python/parquet/parquet_datasets.rst index 6a47d7867e4..c643786934e 100644 --- a/docs/source/python/parquet/parquet_datasets.rst +++ b/docs/source/python/parquet/parquet_datasets.rst @@ -129,6 +129,37 @@ combine and write them manually: ... metadata_collector=metadata_collector ... ) +If writing a partitioned dataset (i.e. with ``partition_cols``), the partition +columns are not stored in the data files themselves, but are encoded in the +directory names. The collected file metadata therefore has a schema without +the partition columns, and the schema passed to +:func:`~pyarrow.parquet.write_metadata` for the ``_metadata`` file needs to +match that: + +.. code-block:: python + + >>> # Write a partitioned dataset and collect metadata information of all written files + >>> metadata_collector = [] + >>> root_path = "dataset_name_2" + >>> partition_cols = ["one", "two"] + >>> pq.write_to_dataset(table, root_path, partition_cols=partition_cols, + ... metadata_collector=metadata_collector) + + >>> # Write the ``_common_metadata`` parquet file with the schema of the + >>> # full dataset, including the partition columns + >>> pq.write_metadata(table.schema, root_path + '/_common_metadata') + + >>> # Write the ``_metadata`` parquet file with row groups statistics of all + >>> # files. The data files do not include the partition columns, so those + >>> # need to be removed from the schema + >>> file_schema = table.schema + >>> for col in partition_cols: + ... file_schema = file_schema.remove(file_schema.get_field_index(col)) + >>> pq.write_metadata( + ... file_schema, root_path + '/_metadata', + ... metadata_collector=metadata_collector + ... ) + When not using the :func:`~pyarrow.parquet.write_to_dataset` function, but writing the individual files of the partitioned dataset using :func:`~pyarrow.parquet.write_table` or :class:`~pyarrow.parquet.ParquetWriter`, diff --git a/python/pyarrow/array.pxi b/python/pyarrow/array.pxi index c4862df5978..a23d224c345 100644 --- a/python/pyarrow/array.pxi +++ b/python/pyarrow/array.pxi @@ -929,6 +929,10 @@ cdef class _PandasConvertible(_Weakrefable): zero_copy_only : bool, default False Raise an ArrowException if this function call would require copying the underlying data. + + When converting a Table or RecordBatch, the columns are converted + as separate pandas blocks (``split_blocks=True``) so that each + column can reference the original Arrow memory. integer_object_nulls : bool, default False Cast integers with nulls to objects date_as_object : bool, default True diff --git a/python/pyarrow/pandas_compat.py b/python/pyarrow/pandas_compat.py index 4ff587b702b..00a8c943b33 100644 --- a/python/pyarrow/pandas_compat.py +++ b/python/pyarrow/pandas_compat.py @@ -795,6 +795,13 @@ def make_datetimetz(unit, tz): def table_to_dataframe( options, table, categories=None, ignore_metadata=False, types_mapper=None ): + # Zero-copy conversion of a Table or RecordBatch into a DataFrame requires + # one pandas block per column, as a multi-column block cannot reference the + # original Arrow memory; this is only supported with ``split_blocks=True`` + if options.get('zero_copy_only') and not options.get('split_blocks'): + options = dict(options) + options['split_blocks'] = True + all_columns = [] column_indexes = [] attributes = {} diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 1f09a9247e6..6a03fc01e4f 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -3004,6 +3004,24 @@ def test_zero_copy_failure_on_duration_with_nulls(self): arr = np.array([1, None], dtype='timedelta64[ns]') self.check_zero_copy_failure(pa.array(arr)) + def test_zero_copy_table_success(self): + # GH-39194: zero-copy conversion of a Table needs one block per + # column, which is enabled automatically for the DataFrame path + table = pa.table({'a': [0, 1, 2], 'b': [0.0, 1.0, 2.0]}) + result = table.to_pandas(zero_copy_only=True) + expected = pd.DataFrame({'a': [0, 1, 2], 'b': [0.0, 1.0, 2.0]}) + tm.assert_frame_equal(result, expected) + + def test_zero_copy_table_failure_when_copy_needed(self): + table = pa.table({'a': [0, 1, None]}) + with pytest.raises(pa.ArrowInvalid): + table.to_pandas(zero_copy_only=True) + + def test_zero_copy_table_failure_with_strings_to_categorical(self): + table = pa.table({'a': ['A', 'B', 'C']}) + with pytest.raises(pa.ArrowInvalid): + table.to_pandas(zero_copy_only=True, strings_to_categorical=True) + def _non_threaded_conversion(): df = _alltypes_example()