jorisvandenbossche commented on code in PR #14804: URL: https://github.com/apache/arrow/pull/14804#discussion_r1053445924
########## python/pyarrow/interchange/from_dataframe.py: ########## @@ -0,0 +1,590 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import ( + Any, +) + +from pyarrow.interchange.column import ( + DtypeKind, + ColumnBuffers, + ColumnNullType, +) + +import ctypes +import numpy as np +import pyarrow as pa +import re + +from pyarrow.interchange.column import Dtype + + +# A typing protocol could be added later to let Mypy validate code using +# `from_dataframe` better. +DataFrameObject = Any +ColumnObject = Any +BufferObject = Any + + +_PYARROW_DTYPES: dict[DtypeKind, dict[int, Any]] = { + DtypeKind.INT: {8: pa.int8(), + 16: pa.int16(), + 32: pa.int32(), + 64: pa.int64()}, + DtypeKind.UINT: {8: pa.uint8(), + 16: pa.uint16(), + 32: pa.uint32(), + 64: pa.uint64()}, + DtypeKind.FLOAT: {16: pa.float16(), + 32: pa.float32(), + 64: pa.float64()}, + DtypeKind.BOOL: {1: pa.bool_()}, + DtypeKind.STRING: {8: pa.string()}, +} + + +def from_dataframe(df: DataFrameObject, allow_copy=True) -> pa.Table: + """ + Build a ``pa.Table`` from any DataFrame supporting the interchange + protocol. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + if isinstance(df, pa.Table): + return df + + if not hasattr(df, "__dataframe__"): + raise ValueError("`df` does not support __dataframe__") + + return _from_dataframe(df.__dataframe__(allow_copy=allow_copy)) + + +def _from_dataframe(df: DataFrameObject, allow_copy=True): + """ + Build a ``pa.Table`` from the DataFrame interchange object. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + batches = [] + for chunk in df.get_chunks(): + batch = protocol_df_chunk_to_pyarrow(chunk, allow_copy) + batches.append(batch) + + table = pa.Table.from_batches(batches) + return table + + +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, + allow_copy: bool = True +) -> pa.Table: + """ + Convert interchange protocol chunk to ``pa.RecordBatch``. + + Parameters + ---------- + df : DataFrameObject + + Returns + ------- + pa.RecordBatch + """ + # We need a dict of columns here, with each column being a PyArrow + # or NumPy array. + columns: dict[str, Any] = {} Review Comment: ```suggestion columns: dict[str, pa.Array] = {} ``` ? ########## python/pyarrow/tests/interchange/test_extra.py: ########## @@ -0,0 +1,371 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from datetime import datetime as dt +import numpy as np +import pyarrow as pa +from pyarrow.vendored.version import Version +import pytest + +import pyarrow.interchange as pi +from pyarrow.interchange.column import ( + _PyArrowColumn, + ColumnNullType, + DtypeKind, +) +from pyarrow.interchange.from_dataframe import _from_dataframe + +try: + import pandas as pd + # import pandas.testing as tm +except ImportError: + pass + + [email protected]("unit", ['s', 'ms', 'us', 'ns']) [email protected]("tz", ['', 'America/New_York', '+07:30', '-04:30']) +def test_datetime(unit, tz): + dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), None] + table = pa.table({"A": pa.array(dt_arr, type=pa.timestamp(unit, tz=tz))}) + col = table.__dataframe__().get_column_by_name("A") + + assert col.size() == 3 + assert col.offset == 0 + assert col.null_count == 1 + assert col.dtype[0] == DtypeKind.DATETIME + assert col.describe_null == (ColumnNullType.USE_BITMASK, 0) + + [email protected]( + ["test_data", "kind"], + [ + (["foo", "bar"], 21), + ([1.5, 2.5, 3.5], 2), + ([1, 2, 3, 4], 0), + ], +) +def test_array_to_pyarrowcolumn(test_data, kind): + arr = pa.array(test_data) + arr_column = _PyArrowColumn(arr) + + assert arr_column._col == arr + assert arr_column.size() == len(test_data) + assert arr_column.dtype[0] == kind + assert arr_column.num_chunks() == 1 + assert arr_column.null_count == 0 + assert arr_column.get_buffers()["validity"] is None + assert len(list(arr_column.get_chunks())) == 1 + + for chunk in arr_column.get_chunks(): + assert chunk == arr_column + + +def test_offset_of_sliced_array(): + arr = pa.array([1, 2, 3, 4]) + arr_sliced = arr.slice(2, 2) + + table = pa.table([arr], names=["arr"]) + table_sliced = pa.table([arr_sliced], names=["arr_sliced"]) + + col = table_sliced.__dataframe__().get_column(0) + assert col.offset == 2 + + result = _from_dataframe(table_sliced.__dataframe__()) + assert table_sliced.equals(result) + assert not table.equals(result) + + # pandas hardcodes offset to 0: + # https://github.com/pandas-dev/pandas/blob/5c66e65d7b9fef47ccb585ce2fd0b3ea18dc82ea/pandas/core/interchange/from_dataframe.py#L247 + # so conversion to pandas can't be tested currently + + # df = pandas_from_dataframe(table) + # df_sliced = pandas_from_dataframe(table_sliced) + + # tm.assert_series_equal(df["arr"][2:4], df_sliced["arr_sliced"], + # check_index=False, check_names=False) + + +# Currently errors due to string conversion +# as col.size is called as a property not method in pandas +# see L255-L257 in pandas/core/interchange/from_dataframe.py [email protected] +def test_categorical_roundtrip(): + pytest.skip("Bug in pandas implementation") + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"] + table = pa.table( + {"weekday": pa.array(arr).dictionary_encode()} + ) + + pandas_df = table.to_pandas() + result = pi.from_dataframe(pandas_df) + + # Checking equality for the values + # As the dtype of the indices is changed from int32 in pa.Table + # to int64 in pandas interchange protocol implementation + assert result[0].chunk(0).dictionary == table[0].chunk(0).dictionary + + table_protocol = table.__dataframe__() + result_protocol = result.__dataframe__() + + assert table_protocol.num_columns() == result_protocol.num_columns() + assert table_protocol.num_rows() == result_protocol.num_rows() + assert table_protocol.num_chunks() == result_protocol.num_chunks() + assert table_protocol.column_names() == result_protocol.column_names() + + col_table = table_protocol.get_column(0) + col_result = result_protocol.get_column(0) + + assert col_result.dtype[0] == DtypeKind.CATEGORICAL + assert col_result.dtype[0] == col_table.dtype[0] + assert col_result.size == col_table.size + assert col_result.offset == col_table.offset + + desc_cat_table = col_result.describe_categorical + desc_cat_result = col_result.describe_categorical + + assert desc_cat_table["is_ordered"] == desc_cat_result["is_ordered"] + assert desc_cat_table["is_dictionary"] == desc_cat_result["is_dictionary"] + assert isinstance(desc_cat_result["categories"]._col, pa.Array) + + [email protected] [email protected]( + "uint", [pa.uint8(), pa.uint16(), pa.uint32()] +) [email protected]( + "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()] +) [email protected]( + "float, np_float", [ + # (pa.float16(), np.float16), #not supported by pandas + (pa.float32(), np.float32), + (pa.float64(), np.float64) + ] +) +def test_pandas_roundtrip(uint, int, float, np_float): + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + arr = [1, 2, 3] + table = pa.table( + { + "a": pa.array(arr, type=uint), + "b": pa.array(arr, type=int), + "c": pa.array(np.array(arr, dtype=np_float), type=float), + # String dtype errors as col.size is called as a property + # not method in pandas, see L255-L257 in + # pandas/core/interchange/from_dataframe.py + # "d": ["a", "", "c"], + # large string is not supported by pandas implementation + } + ) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + pandas_df = pandas_from_dataframe(table) + result = pi.from_dataframe(pandas_df) + assert table.equals(result) + + table_protocol = table.__dataframe__() + result_protocol = result.__dataframe__() + + assert table_protocol.num_columns() == result_protocol.num_columns() + assert table_protocol.num_rows() == result_protocol.num_rows() + assert table_protocol.num_chunks() == result_protocol.num_chunks() + assert table_protocol.column_names() == result_protocol.column_names() + + [email protected] +def test_roundtrip_pandas_boolean(): + # Boolean pyarrow Arrays are casted to uint8 as bit packed boolean + # is not yet supported by the protocol + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + table = pa.table({"a": [True, False, True]}) + expected = pa.table({"a": pa.array([1, 0, 1], type=pa.uint8())}) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + pandas_df = pandas_from_dataframe(table) + result = pi.from_dataframe(pandas_df) + + assert expected.equals(result) + + expected_protocol = expected.__dataframe__() + result_protocol = result.__dataframe__() + + assert expected_protocol.num_columns() == result_protocol.num_columns() + assert expected_protocol.num_rows() == result_protocol.num_rows() + assert expected_protocol.num_chunks() == result_protocol.num_chunks() + assert expected_protocol.column_names() == result_protocol.column_names() + + [email protected] [email protected]("unit", ['s', 'ms', 'us', 'ns']) +def test_roundtrip_pandas_datetime(unit): + # pandas always creates datetime64 in "us" + # resolution, timezones are not yet supported + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + from datetime import datetime as dt + + dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), dt(2007, 7, 15)] + table = pa.table({"a": pa.array(dt_arr, type=pa.timestamp(unit))}) + expected = pa.table({"a": pa.array(dt_arr, type=pa.timestamp('us'))}) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + pandas_df = pandas_from_dataframe(table) + result = pi.from_dataframe(pandas_df) + + assert expected.equals(result) + + expected_protocol = expected.__dataframe__() + result_protocol = result.__dataframe__() + + assert expected_protocol.num_columns() == result_protocol.num_columns() + assert expected_protocol.num_rows() == result_protocol.num_rows() + assert expected_protocol.num_chunks() == result_protocol.num_chunks() + assert expected_protocol.column_names() == result_protocol.column_names() + + [email protected]_memory [email protected] +def test_pandas_assertion_error_large_string(): + # Test AssertionError as pandas does not support "U" type strings + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + data = np.array([b'x'*1024]*(3*1024**2), dtype='object') # 3GB bytes data + arr = pa.array(data, type=pa.large_string()) + table = pa.table([arr], names=["large_string"]) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + + with pytest.raises(AssertionError): + pandas_from_dataframe(table) + + [email protected]( + "uint", [pa.uint8(), pa.uint16(), pa.uint32()] +) [email protected]( + "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()] +) [email protected]( + "float, np_float", [ + (pa.float16(), np.float16), + # (pa.float32(), np.float32), #errors due to inequality in nan + # (pa.float64(), np.float64) #errors due to inequality in nan Review Comment: What's the error exactly? ########## python/pyarrow/interchange/from_dataframe.py: ########## @@ -0,0 +1,590 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import ( + Any, +) + +from pyarrow.interchange.column import ( + DtypeKind, + ColumnBuffers, + ColumnNullType, +) + +import ctypes +import numpy as np +import pyarrow as pa +import re + +from pyarrow.interchange.column import Dtype + + +# A typing protocol could be added later to let Mypy validate code using +# `from_dataframe` better. +DataFrameObject = Any +ColumnObject = Any +BufferObject = Any + + +_PYARROW_DTYPES: dict[DtypeKind, dict[int, Any]] = { + DtypeKind.INT: {8: pa.int8(), + 16: pa.int16(), + 32: pa.int32(), + 64: pa.int64()}, + DtypeKind.UINT: {8: pa.uint8(), + 16: pa.uint16(), + 32: pa.uint32(), + 64: pa.uint64()}, + DtypeKind.FLOAT: {16: pa.float16(), + 32: pa.float32(), + 64: pa.float64()}, + DtypeKind.BOOL: {1: pa.bool_()}, + DtypeKind.STRING: {8: pa.string()}, +} + + +def from_dataframe(df: DataFrameObject, allow_copy=True) -> pa.Table: + """ + Build a ``pa.Table`` from any DataFrame supporting the interchange + protocol. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + if isinstance(df, pa.Table): + return df + + if not hasattr(df, "__dataframe__"): + raise ValueError("`df` does not support __dataframe__") + + return _from_dataframe(df.__dataframe__(allow_copy=allow_copy)) + + +def _from_dataframe(df: DataFrameObject, allow_copy=True): + """ + Build a ``pa.Table`` from the DataFrame interchange object. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + batches = [] + for chunk in df.get_chunks(): + batch = protocol_df_chunk_to_pyarrow(chunk, allow_copy) + batches.append(batch) + + table = pa.Table.from_batches(batches) + return table + + +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, + allow_copy: bool = True +) -> pa.Table: + """ + Convert interchange protocol chunk to ``pa.RecordBatch``. + + Parameters + ---------- + df : DataFrameObject + + Returns + ------- + pa.RecordBatch + """ + # We need a dict of columns here, with each column being a PyArrow + # or NumPy array. + columns: dict[str, Any] = {} + buffers = [] # hold on to buffers, keeps memory alive + for name in df.column_names(): + if not isinstance(name, str): + raise ValueError(f"Column {name} is not a string") + if name in columns: + raise ValueError(f"Column {name} is not unique") + col = df.get_column_by_name(name) + dtype = col.dtype[0] + if dtype in ( + DtypeKind.INT, + DtypeKind.UINT, + DtypeKind.FLOAT, + DtypeKind.STRING, + ): + columns[name], buf = column_to_array(col, allow_copy) + elif dtype == DtypeKind.BOOL: + columns[name], buf = bool_8_column_to_array(col, allow_copy) + elif dtype == DtypeKind.CATEGORICAL: + columns[name], buf = categorical_column_to_dictionary( + col, allow_copy) + elif dtype == DtypeKind.DATETIME: + columns[name], buf = datetime_column_to_array(col, allow_copy) + else: + raise NotImplementedError(f"Data type {dtype} not handled yet") + + buffers.append(buf) Review Comment: The `foreign_buffer` function used below has a `base` argument where you can pass a python object that will be kept alive. ########## python/pyarrow/interchange/dataframe.py: ########## @@ -0,0 +1,199 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations +from typing import ( + Any, + Iterable, + Optional, + Sequence, +) + +import pyarrow as pa + +from pyarrow.interchange.column import _PyArrowColumn + + +class _PyArrowDataFrame: + """ + A data frame class, with only the methods required by the interchange + protocol defined. + + A "data frame" represents an ordered collection of named columns. + A column's "name" must be a unique string. + Columns may be accessed by name or by position. + + This could be a public data frame class, or an object with the methods and + attributes defined on this DataFrame class could be returned from the + ``__dataframe__`` method of a public data frame class in a library adhering + to the dataframe interchange protocol specification. + """ + + def __init__( + self, df: pa.Table, nan_as_null: bool = False, allow_copy: bool = True + ) -> None: + """ + Constructor - an instance of this (private) class is returned from + `pa.Table.__dataframe__`. + """ + self._df = df + # ``nan_as_null`` is a keyword intended for the consumer to tell the + # producer to overwrite null values in the data with ``NaN`` (or + # ``NaT``). This currently has no effect; once support for nullable + # extension dtypes is added, this value should be propagated to + # columns. + if nan_as_null is True: + raise RuntimeError( + "nan_as_null=True currently has no effect, " + "use the default nan_as_null=False" + ) + self._nan_as_null = nan_as_null + self._allow_copy = allow_copy + + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> _PyArrowDataFrame: + """ + Construct a new exchange object, potentially changing the parameters. + ``nan_as_null`` is a keyword intended for the consumer to tell the + producer to overwrite null values in the data with ``NaN``. + It is intended for cases where the consumer does not support the bit + mask or byte mask that is the producer's native representation. + ``allow_copy`` is a keyword that defines whether or not the library is + allowed to make a copy of the data. For example, copying data would be + necessary if a library supports strided buffers, given that this + protocol specifies contiguous buffers. + """ + return _PyArrowDataFrame(self._df, nan_as_null, allow_copy) + + @property + def metadata(self) -> dict[str, Any]: + """ + The metadata for the data frame, as a dictionary with string keys. The + contents of `metadata` may be anything, they are meant for a library + to store information that it needs to, e.g., roundtrip losslessly or + for two implementations to share data that is not (yet) part of the + interchange protocol specification. For avoiding collisions with other + entries, please add name the keys with the name of the library + followed by a period and the desired name, e.g, ``pandas.indexcol``. + """ + # The metadata for the data frame, as a dictionary with string keys. + # Add schema metadata here (pandas metadata or custom metadata) + if self._df.schema.metadata: + schema_metadata = {"pyarrow." + k.decode('utf8'): v.decode('utf8') + for k, v in self._df.schema.metadata.items()} + return schema_metadata + else: + return {} + + def num_columns(self) -> int: + """ + Return the number of columns in the DataFrame. + """ + return self._df.num_columns + + def num_rows(self) -> int: + """ + Return the number of rows in the DataFrame, if available. + """ + return self._df.num_rows + + def num_chunks(self) -> int: + """ + Return the number of chunks the DataFrame consists of. + """ + return self._df.column(0).num_chunks Review Comment: Columns can be differently chunked within a pyarrow.Table. Just checking the first column is probably fine for now, but we should maybe note this caveat in a comment. (and so `self._df.to_batches()` can return a different number of batches) ########## python/pyarrow/interchange/from_dataframe.py: ########## @@ -0,0 +1,590 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import ( + Any, +) + +from pyarrow.interchange.column import ( + DtypeKind, + ColumnBuffers, + ColumnNullType, +) + +import ctypes +import numpy as np +import pyarrow as pa +import re + +from pyarrow.interchange.column import Dtype + + +# A typing protocol could be added later to let Mypy validate code using +# `from_dataframe` better. +DataFrameObject = Any +ColumnObject = Any +BufferObject = Any + + +_PYARROW_DTYPES: dict[DtypeKind, dict[int, Any]] = { + DtypeKind.INT: {8: pa.int8(), + 16: pa.int16(), + 32: pa.int32(), + 64: pa.int64()}, + DtypeKind.UINT: {8: pa.uint8(), + 16: pa.uint16(), + 32: pa.uint32(), + 64: pa.uint64()}, + DtypeKind.FLOAT: {16: pa.float16(), + 32: pa.float32(), + 64: pa.float64()}, + DtypeKind.BOOL: {1: pa.bool_()}, + DtypeKind.STRING: {8: pa.string()}, +} + + +def from_dataframe(df: DataFrameObject, allow_copy=True) -> pa.Table: + """ + Build a ``pa.Table`` from any DataFrame supporting the interchange + protocol. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + if isinstance(df, pa.Table): + return df + + if not hasattr(df, "__dataframe__"): + raise ValueError("`df` does not support __dataframe__") + + return _from_dataframe(df.__dataframe__(allow_copy=allow_copy)) + + +def _from_dataframe(df: DataFrameObject, allow_copy=True): + """ + Build a ``pa.Table`` from the DataFrame interchange object. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + batches = [] + for chunk in df.get_chunks(): + batch = protocol_df_chunk_to_pyarrow(chunk, allow_copy) + batches.append(batch) + + table = pa.Table.from_batches(batches) + return table + + +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, + allow_copy: bool = True +) -> pa.Table: + """ + Convert interchange protocol chunk to ``pa.RecordBatch``. + + Parameters + ---------- + df : DataFrameObject + + Returns + ------- + pa.RecordBatch + """ + # We need a dict of columns here, with each column being a PyArrow + # or NumPy array. + columns: dict[str, Any] = {} + buffers = [] # hold on to buffers, keeps memory alive + for name in df.column_names(): + if not isinstance(name, str): + raise ValueError(f"Column {name} is not a string") + if name in columns: + raise ValueError(f"Column {name} is not unique") + col = df.get_column_by_name(name) + dtype = col.dtype[0] + if dtype in ( + DtypeKind.INT, + DtypeKind.UINT, + DtypeKind.FLOAT, + DtypeKind.STRING, + ): + columns[name], buf = column_to_array(col, allow_copy) + elif dtype == DtypeKind.BOOL: + columns[name], buf = bool_8_column_to_array(col, allow_copy) + elif dtype == DtypeKind.CATEGORICAL: + columns[name], buf = categorical_column_to_dictionary( + col, allow_copy) + elif dtype == DtypeKind.DATETIME: + columns[name], buf = datetime_column_to_array(col, allow_copy) + else: + raise NotImplementedError(f"Data type {dtype} not handled yet") + + buffers.append(buf) + + return pa.RecordBatch.from_pydict(columns) + + +def column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding one of the primitive dtypes to a PyArrow array. + A primitive type is one of: int, uint, float, bool (1 bit). + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + buffers = col.get_buffers() + null_count = col.null_count + data = buffers_to_array(buffers, col.size(), + col.describe_null, + col.dtype, col.offset, + allow_copy, null_count) + return data, buffers + + +def bool_8_column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding boolean dtype with bit width = 8 to a + PyArrow array. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + buffers = col.get_buffers() + + # Data buffer + data_buff, data_dtype = buffers["data"] + offset = col.offset + data_bit_width = data_dtype[1] + + data = buffer_to_ndarray(data_buff, + data_bit_width, + offset) + + # Validity buffer + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + + null_kind, sentinel_val = col.describe_null + bytemask = None + + if validity_buff: + if null_kind in (ColumnNullType.USE_BYTEMASK, + ColumnNullType.USE_BITMASK): + + validity_bit_width = validity_dtype[1] + bytemask = buffer_to_ndarray(validity_buff, + validity_bit_width, + offset) + if sentinel_val == 0: + bytemask = np.invert(bytemask) + else: + raise NotImplementedError(f"{null_kind} null representation " + "is not yet supported for boolean " + "dtype.") + # Output + return pa.array(data, mask=bytemask), buffers + + +def categorical_column_to_dictionary( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.DictionaryArray, Any]: + """ + Convert a column holding categorical data to a pa.DictionaryArray. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.DictionaryArray holding the data and the memory owner + object that keeps the memory alive. + """ + categorical = col.describe_categorical + null_kind, sentinel_val = col.describe_null + + if not categorical["is_dictionary"]: + raise NotImplementedError( + "Non-dictionary categoricals not supported yet") + + cat_column = categorical["categories"] + dictionary = column_to_array(cat_column)[0] + + buffers = col.get_buffers() + indices = buffers_to_array(buffers, col.size(), + col.describe_null, + col.dtype, col.offset, + allow_copy) + + if null_kind == ColumnNullType.USE_SENTINEL: + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + bytemask = [value == sentinel_val for value in indices.to_pylist()] + indices = pa.array(indices.to_pylist(), mask=bytemask) + + dict_array = pa.DictionaryArray.from_arrays(indices, dictionary) + return dict_array, buffers + + +def datetime_column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding DateTime data to a NumPy array. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + buffers = col.get_buffers() + data_buff, data_type = buffers["data"] + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + + format_str = data_type[2] + unit, tz = parse_datetime_format_str(format_str) + data_dtype = pa.timestamp(unit, tz=tz) + + # Data buffer + data_pa_buffer = pa.foreign_buffer(data_buff.ptr, data_buff.bufsize) + + # Validity buffer + validity_pa_buff = validity_buff + bytemask = None + if validity_pa_buff: + validity_pa_buff, bytemask = validity_buffer(validity_buff, + validity_dtype, + col.describe_null, + col.offset) + + # Constructing a pa.Array from data and validity buffer + array = pa.Array.from_buffers( + data_dtype, + col.size(), + [validity_pa_buff, data_pa_buffer], + offset=col.offset, + ) + + null_kind, sentinel_val = col.describe_null + if null_kind == ColumnNullType.USE_SENTINEL: + # pandas iNaT + if sentinel_val == -9223372036854775808: + bytemask = np.isnan(np.array([str(e) for e in array.to_pylist()], + dtype="datetime64[ns]")) Review Comment: Couldn't this be done more efficiently by checking `array == 9223372036854775808`? ########## python/pyarrow/tests/interchange/test_extra.py: ########## @@ -0,0 +1,371 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from datetime import datetime as dt +import numpy as np +import pyarrow as pa +from pyarrow.vendored.version import Version +import pytest + +import pyarrow.interchange as pi +from pyarrow.interchange.column import ( + _PyArrowColumn, + ColumnNullType, + DtypeKind, +) +from pyarrow.interchange.from_dataframe import _from_dataframe + +try: + import pandas as pd + # import pandas.testing as tm +except ImportError: + pass + + [email protected]("unit", ['s', 'ms', 'us', 'ns']) [email protected]("tz", ['', 'America/New_York', '+07:30', '-04:30']) +def test_datetime(unit, tz): + dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), None] + table = pa.table({"A": pa.array(dt_arr, type=pa.timestamp(unit, tz=tz))}) + col = table.__dataframe__().get_column_by_name("A") + + assert col.size() == 3 + assert col.offset == 0 + assert col.null_count == 1 + assert col.dtype[0] == DtypeKind.DATETIME + assert col.describe_null == (ColumnNullType.USE_BITMASK, 0) + + [email protected]( + ["test_data", "kind"], + [ + (["foo", "bar"], 21), + ([1.5, 2.5, 3.5], 2), + ([1, 2, 3, 4], 0), + ], +) +def test_array_to_pyarrowcolumn(test_data, kind): + arr = pa.array(test_data) + arr_column = _PyArrowColumn(arr) + + assert arr_column._col == arr + assert arr_column.size() == len(test_data) + assert arr_column.dtype[0] == kind + assert arr_column.num_chunks() == 1 + assert arr_column.null_count == 0 + assert arr_column.get_buffers()["validity"] is None + assert len(list(arr_column.get_chunks())) == 1 + + for chunk in arr_column.get_chunks(): + assert chunk == arr_column + + +def test_offset_of_sliced_array(): + arr = pa.array([1, 2, 3, 4]) + arr_sliced = arr.slice(2, 2) + + table = pa.table([arr], names=["arr"]) + table_sliced = pa.table([arr_sliced], names=["arr_sliced"]) + + col = table_sliced.__dataframe__().get_column(0) + assert col.offset == 2 + + result = _from_dataframe(table_sliced.__dataframe__()) + assert table_sliced.equals(result) + assert not table.equals(result) + + # pandas hardcodes offset to 0: + # https://github.com/pandas-dev/pandas/blob/5c66e65d7b9fef47ccb585ce2fd0b3ea18dc82ea/pandas/core/interchange/from_dataframe.py#L247 + # so conversion to pandas can't be tested currently + + # df = pandas_from_dataframe(table) + # df_sliced = pandas_from_dataframe(table_sliced) + + # tm.assert_series_equal(df["arr"][2:4], df_sliced["arr_sliced"], + # check_index=False, check_names=False) + + +# Currently errors due to string conversion +# as col.size is called as a property not method in pandas +# see L255-L257 in pandas/core/interchange/from_dataframe.py [email protected] +def test_categorical_roundtrip(): + pytest.skip("Bug in pandas implementation") + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"] + table = pa.table( + {"weekday": pa.array(arr).dictionary_encode()} + ) + + pandas_df = table.to_pandas() + result = pi.from_dataframe(pandas_df) + + # Checking equality for the values + # As the dtype of the indices is changed from int32 in pa.Table + # to int64 in pandas interchange protocol implementation + assert result[0].chunk(0).dictionary == table[0].chunk(0).dictionary + + table_protocol = table.__dataframe__() + result_protocol = result.__dataframe__() + + assert table_protocol.num_columns() == result_protocol.num_columns() + assert table_protocol.num_rows() == result_protocol.num_rows() + assert table_protocol.num_chunks() == result_protocol.num_chunks() + assert table_protocol.column_names() == result_protocol.column_names() + + col_table = table_protocol.get_column(0) + col_result = result_protocol.get_column(0) + + assert col_result.dtype[0] == DtypeKind.CATEGORICAL + assert col_result.dtype[0] == col_table.dtype[0] + assert col_result.size == col_table.size + assert col_result.offset == col_table.offset + + desc_cat_table = col_result.describe_categorical + desc_cat_result = col_result.describe_categorical + + assert desc_cat_table["is_ordered"] == desc_cat_result["is_ordered"] + assert desc_cat_table["is_dictionary"] == desc_cat_result["is_dictionary"] + assert isinstance(desc_cat_result["categories"]._col, pa.Array) + + [email protected] [email protected]( + "uint", [pa.uint8(), pa.uint16(), pa.uint32()] +) [email protected]( + "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()] +) [email protected]( + "float, np_float", [ + # (pa.float16(), np.float16), #not supported by pandas + (pa.float32(), np.float32), + (pa.float64(), np.float64) + ] +) +def test_pandas_roundtrip(uint, int, float, np_float): + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + arr = [1, 2, 3] + table = pa.table( + { + "a": pa.array(arr, type=uint), + "b": pa.array(arr, type=int), + "c": pa.array(np.array(arr, dtype=np_float), type=float), + # String dtype errors as col.size is called as a property + # not method in pandas, see L255-L257 in + # pandas/core/interchange/from_dataframe.py + # "d": ["a", "", "c"], + # large string is not supported by pandas implementation + } + ) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + pandas_df = pandas_from_dataframe(table) + result = pi.from_dataframe(pandas_df) + assert table.equals(result) + + table_protocol = table.__dataframe__() + result_protocol = result.__dataframe__() + + assert table_protocol.num_columns() == result_protocol.num_columns() + assert table_protocol.num_rows() == result_protocol.num_rows() + assert table_protocol.num_chunks() == result_protocol.num_chunks() + assert table_protocol.column_names() == result_protocol.column_names() + + [email protected] +def test_roundtrip_pandas_boolean(): + # Boolean pyarrow Arrays are casted to uint8 as bit packed boolean + # is not yet supported by the protocol + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + table = pa.table({"a": [True, False, True]}) + expected = pa.table({"a": pa.array([1, 0, 1], type=pa.uint8())}) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + pandas_df = pandas_from_dataframe(table) + result = pi.from_dataframe(pandas_df) + + assert expected.equals(result) + + expected_protocol = expected.__dataframe__() + result_protocol = result.__dataframe__() + + assert expected_protocol.num_columns() == result_protocol.num_columns() + assert expected_protocol.num_rows() == result_protocol.num_rows() + assert expected_protocol.num_chunks() == result_protocol.num_chunks() + assert expected_protocol.column_names() == result_protocol.column_names() + + [email protected] [email protected]("unit", ['s', 'ms', 'us', 'ns']) +def test_roundtrip_pandas_datetime(unit): + # pandas always creates datetime64 in "us" + # resolution, timezones are not yet supported + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + from datetime import datetime as dt + + dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), dt(2007, 7, 15)] + table = pa.table({"a": pa.array(dt_arr, type=pa.timestamp(unit))}) + expected = pa.table({"a": pa.array(dt_arr, type=pa.timestamp('us'))}) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + pandas_df = pandas_from_dataframe(table) + result = pi.from_dataframe(pandas_df) + + assert expected.equals(result) + + expected_protocol = expected.__dataframe__() + result_protocol = result.__dataframe__() + + assert expected_protocol.num_columns() == result_protocol.num_columns() + assert expected_protocol.num_rows() == result_protocol.num_rows() + assert expected_protocol.num_chunks() == result_protocol.num_chunks() + assert expected_protocol.column_names() == result_protocol.column_names() + + [email protected]_memory [email protected] +def test_pandas_assertion_error_large_string(): + # Test AssertionError as pandas does not support "U" type strings + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + data = np.array([b'x'*1024]*(3*1024**2), dtype='object') # 3GB bytes data + arr = pa.array(data, type=pa.large_string()) + table = pa.table([arr], names=["large_string"]) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe + ) + + with pytest.raises(AssertionError): + pandas_from_dataframe(table) + + [email protected]( + "uint", [pa.uint8(), pa.uint16(), pa.uint32()] +) [email protected]( + "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()] +) [email protected]( + "float, np_float", [ + (pa.float16(), np.float16), + # (pa.float32(), np.float32), #errors due to inequality in nan + # (pa.float64(), np.float64) #errors due to inequality in nan + ] +) [email protected]("unit", ['s', 'ms', 'us', 'ns']) [email protected]("tz", ['America/New_York', '+07:30', '-04:30']) +def test_pyarrow_roundtrip(uint, int, float, np_float, unit, tz): Review Comment: In this one we can maybe parametrize it for being sliced as well (eg `table = table.slice(1, 1)` before doing the roundtrip) ########## python/pyarrow/tests/interchange/test_extra.py: ########## @@ -0,0 +1,371 @@ +# Licensed to the Apache Software Foundation (ASF) under one Review Comment: Maybe call this file something like `test_conversion.py`? (more descriptive than `test_extra.py`, and I think this file is mostly checking the actual conversion, and the other file is more testing the API of the spec object?) ########## python/pyarrow/interchange/from_dataframe.py: ########## @@ -0,0 +1,590 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import ( + Any, +) + +from pyarrow.interchange.column import ( + DtypeKind, + ColumnBuffers, + ColumnNullType, +) + +import ctypes +import numpy as np +import pyarrow as pa +import re + +from pyarrow.interchange.column import Dtype + + +# A typing protocol could be added later to let Mypy validate code using +# `from_dataframe` better. +DataFrameObject = Any +ColumnObject = Any +BufferObject = Any + + +_PYARROW_DTYPES: dict[DtypeKind, dict[int, Any]] = { + DtypeKind.INT: {8: pa.int8(), + 16: pa.int16(), + 32: pa.int32(), + 64: pa.int64()}, + DtypeKind.UINT: {8: pa.uint8(), + 16: pa.uint16(), + 32: pa.uint32(), + 64: pa.uint64()}, + DtypeKind.FLOAT: {16: pa.float16(), + 32: pa.float32(), + 64: pa.float64()}, + DtypeKind.BOOL: {1: pa.bool_()}, + DtypeKind.STRING: {8: pa.string()}, +} + + +def from_dataframe(df: DataFrameObject, allow_copy=True) -> pa.Table: + """ + Build a ``pa.Table`` from any DataFrame supporting the interchange + protocol. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + if isinstance(df, pa.Table): + return df + + if not hasattr(df, "__dataframe__"): + raise ValueError("`df` does not support __dataframe__") + + return _from_dataframe(df.__dataframe__(allow_copy=allow_copy)) + + +def _from_dataframe(df: DataFrameObject, allow_copy=True): + """ + Build a ``pa.Table`` from the DataFrame interchange object. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + batches = [] + for chunk in df.get_chunks(): + batch = protocol_df_chunk_to_pyarrow(chunk, allow_copy) + batches.append(batch) + + table = pa.Table.from_batches(batches) + return table + + +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, + allow_copy: bool = True +) -> pa.Table: + """ + Convert interchange protocol chunk to ``pa.RecordBatch``. + + Parameters + ---------- + df : DataFrameObject + + Returns + ------- + pa.RecordBatch + """ + # We need a dict of columns here, with each column being a PyArrow + # or NumPy array. + columns: dict[str, Any] = {} + buffers = [] # hold on to buffers, keeps memory alive + for name in df.column_names(): + if not isinstance(name, str): + raise ValueError(f"Column {name} is not a string") + if name in columns: + raise ValueError(f"Column {name} is not unique") + col = df.get_column_by_name(name) + dtype = col.dtype[0] + if dtype in ( + DtypeKind.INT, + DtypeKind.UINT, + DtypeKind.FLOAT, + DtypeKind.STRING, + ): + columns[name], buf = column_to_array(col, allow_copy) + elif dtype == DtypeKind.BOOL: + columns[name], buf = bool_8_column_to_array(col, allow_copy) + elif dtype == DtypeKind.CATEGORICAL: + columns[name], buf = categorical_column_to_dictionary( + col, allow_copy) + elif dtype == DtypeKind.DATETIME: + columns[name], buf = datetime_column_to_array(col, allow_copy) + else: + raise NotImplementedError(f"Data type {dtype} not handled yet") + + buffers.append(buf) + + return pa.RecordBatch.from_pydict(columns) + + +def column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding one of the primitive dtypes to a PyArrow array. + A primitive type is one of: int, uint, float, bool (1 bit). + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + buffers = col.get_buffers() + null_count = col.null_count + data = buffers_to_array(buffers, col.size(), + col.describe_null, + col.dtype, col.offset, + allow_copy, null_count) + return data, buffers + + +def bool_8_column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding boolean dtype with bit width = 8 to a + PyArrow array. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + buffers = col.get_buffers() + + # Data buffer + data_buff, data_dtype = buffers["data"] + offset = col.offset + data_bit_width = data_dtype[1] + + data = buffer_to_ndarray(data_buff, + data_bit_width, + offset) + + # Validity buffer + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + + null_kind, sentinel_val = col.describe_null + bytemask = None + + if validity_buff: + if null_kind in (ColumnNullType.USE_BYTEMASK, + ColumnNullType.USE_BITMASK): + + validity_bit_width = validity_dtype[1] + bytemask = buffer_to_ndarray(validity_buff, + validity_bit_width, + offset) + if sentinel_val == 0: + bytemask = np.invert(bytemask) + else: + raise NotImplementedError(f"{null_kind} null representation " + "is not yet supported for boolean " + "dtype.") + # Output + return pa.array(data, mask=bytemask), buffers + + +def categorical_column_to_dictionary( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.DictionaryArray, Any]: + """ + Convert a column holding categorical data to a pa.DictionaryArray. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.DictionaryArray holding the data and the memory owner + object that keeps the memory alive. + """ + categorical = col.describe_categorical + null_kind, sentinel_val = col.describe_null + + if not categorical["is_dictionary"]: + raise NotImplementedError( + "Non-dictionary categoricals not supported yet") + + cat_column = categorical["categories"] + dictionary = column_to_array(cat_column)[0] + + buffers = col.get_buffers() + indices = buffers_to_array(buffers, col.size(), + col.describe_null, + col.dtype, col.offset, + allow_copy) + + if null_kind == ColumnNullType.USE_SENTINEL: + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + bytemask = [value == sentinel_val for value in indices.to_pylist()] + indices = pa.array(indices.to_pylist(), mask=bytemask) + + dict_array = pa.DictionaryArray.from_arrays(indices, dictionary) + return dict_array, buffers + + +def datetime_column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding DateTime data to a NumPy array. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + buffers = col.get_buffers() + data_buff, data_type = buffers["data"] + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + + format_str = data_type[2] + unit, tz = parse_datetime_format_str(format_str) + data_dtype = pa.timestamp(unit, tz=tz) + + # Data buffer + data_pa_buffer = pa.foreign_buffer(data_buff.ptr, data_buff.bufsize) + + # Validity buffer + validity_pa_buff = validity_buff + bytemask = None + if validity_pa_buff: + validity_pa_buff, bytemask = validity_buffer(validity_buff, + validity_dtype, + col.describe_null, + col.offset) + + # Constructing a pa.Array from data and validity buffer + array = pa.Array.from_buffers( + data_dtype, + col.size(), + [validity_pa_buff, data_pa_buffer], + offset=col.offset, + ) + + null_kind, sentinel_val = col.describe_null + if null_kind == ColumnNullType.USE_SENTINEL: + # pandas iNaT + if sentinel_val == -9223372036854775808: + bytemask = np.isnan(np.array([str(e) for e in array.to_pylist()], + dtype="datetime64[ns]")) + else: + raise NotImplementedError( + f"Sentinel value {sentinel_val} for datetime is not yet " + "supported.") + + # In case a bytemask was constructed with validity_buffer() call + # or with sentinel_value then we have to add the mask to the array + if bytemask is not None: + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + return pa.array(array.to_pylist(), mask=bytemask), buffers Review Comment: We should make this easier to create a new array from an existing array + new validity bitmap or mask, without the need to go through `to_pylist`. https://issues.apache.org/jira/browse/ARROW-7071 might be a related feature request. Although in this case, doing `array.to_numpy()` might be OK as well? (conversion to numpy should be cheaper than to a python list) ########## python/pyarrow/interchange/from_dataframe.py: ########## @@ -0,0 +1,590 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import ( + Any, +) + +from pyarrow.interchange.column import ( + DtypeKind, + ColumnBuffers, + ColumnNullType, +) + +import ctypes +import numpy as np +import pyarrow as pa +import re + +from pyarrow.interchange.column import Dtype + + +# A typing protocol could be added later to let Mypy validate code using +# `from_dataframe` better. +DataFrameObject = Any +ColumnObject = Any +BufferObject = Any + + +_PYARROW_DTYPES: dict[DtypeKind, dict[int, Any]] = { + DtypeKind.INT: {8: pa.int8(), + 16: pa.int16(), + 32: pa.int32(), + 64: pa.int64()}, + DtypeKind.UINT: {8: pa.uint8(), + 16: pa.uint16(), + 32: pa.uint32(), + 64: pa.uint64()}, + DtypeKind.FLOAT: {16: pa.float16(), + 32: pa.float32(), + 64: pa.float64()}, + DtypeKind.BOOL: {1: pa.bool_()}, + DtypeKind.STRING: {8: pa.string()}, +} + + +def from_dataframe(df: DataFrameObject, allow_copy=True) -> pa.Table: + """ + Build a ``pa.Table`` from any DataFrame supporting the interchange + protocol. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + if isinstance(df, pa.Table): + return df + + if not hasattr(df, "__dataframe__"): + raise ValueError("`df` does not support __dataframe__") + + return _from_dataframe(df.__dataframe__(allow_copy=allow_copy)) + + +def _from_dataframe(df: DataFrameObject, allow_copy=True): + """ + Build a ``pa.Table`` from the DataFrame interchange object. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + batches = [] + for chunk in df.get_chunks(): + batch = protocol_df_chunk_to_pyarrow(chunk, allow_copy) + batches.append(batch) + + table = pa.Table.from_batches(batches) + return table + + +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, + allow_copy: bool = True +) -> pa.Table: + """ + Convert interchange protocol chunk to ``pa.RecordBatch``. + + Parameters + ---------- + df : DataFrameObject + + Returns + ------- + pa.RecordBatch + """ + # We need a dict of columns here, with each column being a PyArrow + # or NumPy array. + columns: dict[str, Any] = {} + buffers = [] # hold on to buffers, keeps memory alive + for name in df.column_names(): + if not isinstance(name, str): + raise ValueError(f"Column {name} is not a string") + if name in columns: + raise ValueError(f"Column {name} is not unique") + col = df.get_column_by_name(name) + dtype = col.dtype[0] + if dtype in ( + DtypeKind.INT, + DtypeKind.UINT, + DtypeKind.FLOAT, + DtypeKind.STRING, + ): + columns[name], buf = column_to_array(col, allow_copy) + elif dtype == DtypeKind.BOOL: + columns[name], buf = bool_8_column_to_array(col, allow_copy) + elif dtype == DtypeKind.CATEGORICAL: + columns[name], buf = categorical_column_to_dictionary( + col, allow_copy) + elif dtype == DtypeKind.DATETIME: + columns[name], buf = datetime_column_to_array(col, allow_copy) + else: + raise NotImplementedError(f"Data type {dtype} not handled yet") + + buffers.append(buf) Review Comment: We are gathering those buffers, but then afterwards don't do anything with this. In the pandas implementation, those buffers were stored privately on the resulting pandas.DataFrame. ########## python/pyarrow/interchange/from_dataframe.py: ########## @@ -0,0 +1,590 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import ( + Any, +) + +from pyarrow.interchange.column import ( + DtypeKind, + ColumnBuffers, + ColumnNullType, +) + +import ctypes +import numpy as np +import pyarrow as pa +import re + +from pyarrow.interchange.column import Dtype + + +# A typing protocol could be added later to let Mypy validate code using +# `from_dataframe` better. +DataFrameObject = Any +ColumnObject = Any +BufferObject = Any + + +_PYARROW_DTYPES: dict[DtypeKind, dict[int, Any]] = { + DtypeKind.INT: {8: pa.int8(), + 16: pa.int16(), + 32: pa.int32(), + 64: pa.int64()}, + DtypeKind.UINT: {8: pa.uint8(), + 16: pa.uint16(), + 32: pa.uint32(), + 64: pa.uint64()}, + DtypeKind.FLOAT: {16: pa.float16(), + 32: pa.float32(), + 64: pa.float64()}, + DtypeKind.BOOL: {1: pa.bool_()}, + DtypeKind.STRING: {8: pa.string()}, +} + + +def from_dataframe(df: DataFrameObject, allow_copy=True) -> pa.Table: + """ + Build a ``pa.Table`` from any DataFrame supporting the interchange + protocol. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + if isinstance(df, pa.Table): + return df + + if not hasattr(df, "__dataframe__"): + raise ValueError("`df` does not support __dataframe__") + + return _from_dataframe(df.__dataframe__(allow_copy=allow_copy)) + + +def _from_dataframe(df: DataFrameObject, allow_copy=True): + """ + Build a ``pa.Table`` from the DataFrame interchange object. + + Parameters + ---------- + df : DataFrameObject + Object supporting the interchange protocol, i.e. `__dataframe__` + method. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + + Returns + ------- + pa.Table + """ + batches = [] + for chunk in df.get_chunks(): + batch = protocol_df_chunk_to_pyarrow(chunk, allow_copy) + batches.append(batch) + + table = pa.Table.from_batches(batches) + return table + + +def protocol_df_chunk_to_pyarrow( + df: DataFrameObject, + allow_copy: bool = True +) -> pa.Table: + """ + Convert interchange protocol chunk to ``pa.RecordBatch``. + + Parameters + ---------- + df : DataFrameObject + + Returns + ------- + pa.RecordBatch + """ + # We need a dict of columns here, with each column being a PyArrow + # or NumPy array. + columns: dict[str, Any] = {} + buffers = [] # hold on to buffers, keeps memory alive + for name in df.column_names(): + if not isinstance(name, str): + raise ValueError(f"Column {name} is not a string") + if name in columns: + raise ValueError(f"Column {name} is not unique") + col = df.get_column_by_name(name) + dtype = col.dtype[0] + if dtype in ( + DtypeKind.INT, + DtypeKind.UINT, + DtypeKind.FLOAT, + DtypeKind.STRING, + ): + columns[name], buf = column_to_array(col, allow_copy) + elif dtype == DtypeKind.BOOL: + columns[name], buf = bool_8_column_to_array(col, allow_copy) + elif dtype == DtypeKind.CATEGORICAL: + columns[name], buf = categorical_column_to_dictionary( + col, allow_copy) + elif dtype == DtypeKind.DATETIME: + columns[name], buf = datetime_column_to_array(col, allow_copy) + else: + raise NotImplementedError(f"Data type {dtype} not handled yet") + + buffers.append(buf) + + return pa.RecordBatch.from_pydict(columns) + + +def column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding one of the primitive dtypes to a PyArrow array. + A primitive type is one of: int, uint, float, bool (1 bit). + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + buffers = col.get_buffers() + null_count = col.null_count + data = buffers_to_array(buffers, col.size(), + col.describe_null, + col.dtype, col.offset, + allow_copy, null_count) + return data, buffers + + +def bool_8_column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding boolean dtype with bit width = 8 to a + PyArrow array. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + buffers = col.get_buffers() + + # Data buffer + data_buff, data_dtype = buffers["data"] + offset = col.offset + data_bit_width = data_dtype[1] + + data = buffer_to_ndarray(data_buff, + data_bit_width, + offset) + + # Validity buffer + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + + null_kind, sentinel_val = col.describe_null + bytemask = None + + if validity_buff: + if null_kind in (ColumnNullType.USE_BYTEMASK, + ColumnNullType.USE_BITMASK): + + validity_bit_width = validity_dtype[1] + bytemask = buffer_to_ndarray(validity_buff, + validity_bit_width, + offset) + if sentinel_val == 0: + bytemask = np.invert(bytemask) + else: + raise NotImplementedError(f"{null_kind} null representation " + "is not yet supported for boolean " + "dtype.") + # Output + return pa.array(data, mask=bytemask), buffers + + +def categorical_column_to_dictionary( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.DictionaryArray, Any]: + """ + Convert a column holding categorical data to a pa.DictionaryArray. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.DictionaryArray holding the data and the memory owner + object that keeps the memory alive. + """ + categorical = col.describe_categorical + null_kind, sentinel_val = col.describe_null + + if not categorical["is_dictionary"]: + raise NotImplementedError( + "Non-dictionary categoricals not supported yet") + + cat_column = categorical["categories"] + dictionary = column_to_array(cat_column)[0] + + buffers = col.get_buffers() + indices = buffers_to_array(buffers, col.size(), + col.describe_null, + col.dtype, col.offset, + allow_copy) + + if null_kind == ColumnNullType.USE_SENTINEL: + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + bytemask = [value == sentinel_val for value in indices.to_pylist()] + indices = pa.array(indices.to_pylist(), mask=bytemask) + + dict_array = pa.DictionaryArray.from_arrays(indices, dictionary) + return dict_array, buffers + + +def datetime_column_to_array( + col: ColumnObject, + allow_copy: bool = True +) -> tuple[pa.Array, Any]: + """ + Convert a column holding DateTime data to a NumPy array. + + Parameters + ---------- + col : ColumnObject + + Returns + ------- + tuple + Tuple of pa.Array holding the data and the memory owner object + that keeps the memory alive. + """ + buffers = col.get_buffers() + data_buff, data_type = buffers["data"] + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + + format_str = data_type[2] + unit, tz = parse_datetime_format_str(format_str) + data_dtype = pa.timestamp(unit, tz=tz) + + # Data buffer + data_pa_buffer = pa.foreign_buffer(data_buff.ptr, data_buff.bufsize) + + # Validity buffer + validity_pa_buff = validity_buff + bytemask = None + if validity_pa_buff: + validity_pa_buff, bytemask = validity_buffer(validity_buff, + validity_dtype, + col.describe_null, + col.offset) + + # Constructing a pa.Array from data and validity buffer + array = pa.Array.from_buffers( + data_dtype, + col.size(), + [validity_pa_buff, data_pa_buffer], + offset=col.offset, + ) + + null_kind, sentinel_val = col.describe_null + if null_kind == ColumnNullType.USE_SENTINEL: + # pandas iNaT + if sentinel_val == -9223372036854775808: + bytemask = np.isnan(np.array([str(e) for e in array.to_pylist()], + dtype="datetime64[ns]")) + else: + raise NotImplementedError( + f"Sentinel value {sentinel_val} for datetime is not yet " + "supported.") + + # In case a bytemask was constructed with validity_buffer() call + # or with sentinel_value then we have to add the mask to the array + if bytemask is not None: + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + return pa.array(array.to_pylist(), mask=bytemask), buffers + else: + return array, buffers + + +def parse_datetime_format_str(format_str): + """Parse datetime `format_str` to interpret the `data`.""" + + # timestamp 'ts{unit}:tz' + timestamp_meta = re.match(r"ts([smun]):(.*)", format_str) + if timestamp_meta: + unit, tz = timestamp_meta.group(1), timestamp_meta.group(2) + if unit != "s": + # the format string describes only a first letter of the unit, so + # add one extra letter to convert the unit to numpy-style: + # 'm' -> 'ms', 'u' -> 'us', 'n' -> 'ns' + unit += "s" + + return unit, tz + + raise NotImplementedError(f"DateTime kind is not supported: {format_str}") + + +def buffers_to_array( + buffers: ColumnBuffers, + length: int, + describe_null: ColumnNullType, + validity_dtype: Dtype, + offset: int = 0, + allow_copy: bool = True, + null_count: int = -1 +) -> pa.Array: + """ + Build a PyArrow array from the passed buffer. + + Parameters + ---------- + buffer : ColumnBuffers + Dictionary containing tuples of underlying buffers and + their associated dtype. + length : int + The number of values in the array. + describe_null: ColumnNullType + Null representation the column dtype uses, + as a tuple ``(kind, value)`` + validity_dtype : Dtype, + Dtype description as a tuple ``(kind, bit-width, format string, + endianness)``. + offset : int, default: 0 + Number of elements to offset from the start of the buffer. + allow_copy : bool, default: True + Whether to allow copying the memory to perform the conversion + (if false then zero-copy approach is requested). + null_count : int, default: -1 + + Returns + ------- + pa.Array + + Notes + ----- + The returned array doesn't own the memory. The caller of this function + is responsible for keeping the memory owner object alive as long as + the returned PyArrow array is being used. + """ + data_buff, data_type = buffers["data"] + try: + validity_buff, validity_dtype = buffers["validity"] + except TypeError: + validity_buff = None + try: + offset_buff, _ = buffers["offsets"] + except TypeError: + offset_buff = None + + kind, bit_width, _, _ = data_type + + data_dtype = _PYARROW_DTYPES.get(kind, {}).get(bit_width, None) + if data_dtype is None: + raise NotImplementedError( + f"Conversion for {data_type} is not yet supported.") + + # Construct a pyarrow Buffer + data_pa_buffer = pa.foreign_buffer(data_buff.ptr, data_buff.bufsize) + + # Construct a validity pyarrow Buffer or a bytemask, if exists + validity_pa_buff = validity_buff + _, _, validity_f_string, _ = validity_dtype + bytemask = None + if validity_pa_buff: + validity_pa_buff, bytemask = validity_buffer(validity_buff, + validity_dtype, + describe_null, + offset) + + # Construct a pyarrow Array from buffers + if offset_buff: + # If an offset buffer exists, construct an offset pyarrow Buffer + # and add it to the construction of an array + offset_pa_buffer = pa.py_buffer(offset_buff._x) + if validity_f_string == 'U': + if not null_count: + null_count = -1 + array = pa.LargeStringArray.from_buffers( + length, + offset_pa_buffer, + data_pa_buffer, + validity_pa_buff, + null_count=null_count, + offset=offset, + ) + else: + array = pa.Array.from_buffers( + pa.string(), + length, + [validity_pa_buff, offset_pa_buffer, data_pa_buffer], + offset=offset, + ) + else: + array = pa.Array.from_buffers( + data_dtype, + length, + [validity_pa_buff, data_pa_buffer], + offset=offset, + ) + + # In case a bytemask was constructed with validity_buffer() call + # then we have to add the mask to the array + if bytemask is not None: + if not allow_copy: + raise RuntimeError( + "PyArrow Array will always be created out of a NumPy ndarray " + "and a copy is required which is forbidden by allow_copy=False" + ) + return pa.array(array.to_pylist(), mask=bytemask) + else: + return array + + +def validity_buffer( + validity_buff: BufferObject, + validity_dtype: Dtype, + describe_null: ColumnNullType, + offset: int = 0, +) -> tuple[pa.Buffer, np.ndarray]: + """ + Build a PyArrow buffer or a NumPy array from the passed buffer. + + Parameters + ---------- + validity_buff : BufferObject + Tuple of underlying validity buffer and associated dtype. + validity_dtype : Dtype + Dtype description as a tuple ``(kind, bit-width, format string, + endianness)``. + describe_null : ColumnNullType + Null representation the column dtype uses, + as a tuple ``(kind, value)`` + offset : int, default: 0 + Number of elements to offset from the start of the buffer. + + Returns + ------- + tuple + Tuple of a pyarrow buffer and a np.ndarray defining a mask. + Ony one of both can be not None. + """ + null_kind, sentinel_val = describe_null + validity_kind, validity_bit_width, _, _ = validity_dtype + assert validity_kind == DtypeKind.BOOL + + bytemask = None + if null_kind == ColumnNullType.USE_BYTEMASK: + + bytemask = buffer_to_ndarray(validity_buff, + validity_bit_width, + offset) + if sentinel_val == 0: + bytemask = np.invert(bytemask) + validity_pa_buff = None + + elif null_kind == ColumnNullType.USE_BITMASK and sentinel_val == 0: + validity_pa_buff = pa.foreign_buffer( + validity_buff.ptr, validity_buff.bufsize) + else: + raise NotImplementedError( + f"{describe_null} null representation is not yet supported.") + + return validity_pa_buff, bytemask + + +def buffer_to_ndarray( Review Comment: Why do we need this helper for a bytemask? I would assume we can take the same approach as for int8 arrays? (which would go through pa.foreign_buffer and pa.Array.from_buffers) ########## python/pyarrow/tests/interchange/test_extra.py: ########## @@ -0,0 +1,371 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from datetime import datetime as dt +import numpy as np +import pyarrow as pa +from pyarrow.vendored.version import Version +import pytest + +import pyarrow.interchange as pi +from pyarrow.interchange.column import ( + _PyArrowColumn, + ColumnNullType, + DtypeKind, +) +from pyarrow.interchange.from_dataframe import _from_dataframe + +try: + import pandas as pd + # import pandas.testing as tm +except ImportError: + pass + + [email protected]("unit", ['s', 'ms', 'us', 'ns']) [email protected]("tz", ['', 'America/New_York', '+07:30', '-04:30']) +def test_datetime(unit, tz): + dt_arr = [dt(2007, 7, 13), dt(2007, 7, 14), None] + table = pa.table({"A": pa.array(dt_arr, type=pa.timestamp(unit, tz=tz))}) + col = table.__dataframe__().get_column_by_name("A") + + assert col.size() == 3 + assert col.offset == 0 + assert col.null_count == 1 + assert col.dtype[0] == DtypeKind.DATETIME + assert col.describe_null == (ColumnNullType.USE_BITMASK, 0) + + [email protected]( + ["test_data", "kind"], + [ + (["foo", "bar"], 21), + ([1.5, 2.5, 3.5], 2), + ([1, 2, 3, 4], 0), + ], +) +def test_array_to_pyarrowcolumn(test_data, kind): + arr = pa.array(test_data) + arr_column = _PyArrowColumn(arr) + + assert arr_column._col == arr + assert arr_column.size() == len(test_data) + assert arr_column.dtype[0] == kind + assert arr_column.num_chunks() == 1 + assert arr_column.null_count == 0 + assert arr_column.get_buffers()["validity"] is None + assert len(list(arr_column.get_chunks())) == 1 + + for chunk in arr_column.get_chunks(): + assert chunk == arr_column + + +def test_offset_of_sliced_array(): + arr = pa.array([1, 2, 3, 4]) + arr_sliced = arr.slice(2, 2) + + table = pa.table([arr], names=["arr"]) + table_sliced = pa.table([arr_sliced], names=["arr_sliced"]) + + col = table_sliced.__dataframe__().get_column(0) + assert col.offset == 2 + + result = _from_dataframe(table_sliced.__dataframe__()) + assert table_sliced.equals(result) + assert not table.equals(result) + + # pandas hardcodes offset to 0: + # https://github.com/pandas-dev/pandas/blob/5c66e65d7b9fef47ccb585ce2fd0b3ea18dc82ea/pandas/core/interchange/from_dataframe.py#L247 + # so conversion to pandas can't be tested currently + + # df = pandas_from_dataframe(table) + # df_sliced = pandas_from_dataframe(table_sliced) + + # tm.assert_series_equal(df["arr"][2:4], df_sliced["arr_sliced"], + # check_index=False, check_names=False) + + +# Currently errors due to string conversion +# as col.size is called as a property not method in pandas +# see L255-L257 in pandas/core/interchange/from_dataframe.py [email protected] +def test_categorical_roundtrip(): + pytest.skip("Bug in pandas implementation") + + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + arr = ["Mon", "Tue", "Mon", "Wed", "Mon", "Thu", "Fri", "Sat", "Sun"] + table = pa.table( + {"weekday": pa.array(arr).dictionary_encode()} + ) + + pandas_df = table.to_pandas() + result = pi.from_dataframe(pandas_df) + + # Checking equality for the values + # As the dtype of the indices is changed from int32 in pa.Table + # to int64 in pandas interchange protocol implementation + assert result[0].chunk(0).dictionary == table[0].chunk(0).dictionary + + table_protocol = table.__dataframe__() + result_protocol = result.__dataframe__() + + assert table_protocol.num_columns() == result_protocol.num_columns() + assert table_protocol.num_rows() == result_protocol.num_rows() + assert table_protocol.num_chunks() == result_protocol.num_chunks() + assert table_protocol.column_names() == result_protocol.column_names() + + col_table = table_protocol.get_column(0) + col_result = result_protocol.get_column(0) + + assert col_result.dtype[0] == DtypeKind.CATEGORICAL + assert col_result.dtype[0] == col_table.dtype[0] + assert col_result.size == col_table.size + assert col_result.offset == col_table.offset + + desc_cat_table = col_result.describe_categorical + desc_cat_result = col_result.describe_categorical + + assert desc_cat_table["is_ordered"] == desc_cat_result["is_ordered"] + assert desc_cat_table["is_dictionary"] == desc_cat_result["is_dictionary"] + assert isinstance(desc_cat_result["categories"]._col, pa.Array) + + [email protected] [email protected]( + "uint", [pa.uint8(), pa.uint16(), pa.uint32()] +) [email protected]( + "int", [pa.int8(), pa.int16(), pa.int32(), pa.int64()] +) [email protected]( + "float, np_float", [ + # (pa.float16(), np.float16), #not supported by pandas + (pa.float32(), np.float32), + (pa.float64(), np.float64) + ] +) +def test_pandas_roundtrip(uint, int, float, np_float): + if Version(pd.__version__) < Version("1.5.0"): + pytest.skip("__dataframe__ added to pandas in 1.5.0") + + arr = [1, 2, 3] + table = pa.table( + { + "a": pa.array(arr, type=uint), + "b": pa.array(arr, type=int), + "c": pa.array(np.array(arr, dtype=np_float), type=float), + # String dtype errors as col.size is called as a property + # not method in pandas, see L255-L257 in + # pandas/core/interchange/from_dataframe.py + # "d": ["a", "", "c"], + # large string is not supported by pandas implementation + } + ) + + from pandas.core.interchange.from_dataframe import ( + from_dataframe as pandas_from_dataframe Review Comment: You can import this from `pandas.api.interchange` (that is considered the public exposed location) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
