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
50 changes: 48 additions & 2 deletions python/pyarrow/pandas_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,14 +1048,60 @@ def _extract_index_level(table, result_table, field_name,
return result_table, None, None

col = table.column(i)
index_level = col.to_pandas(types_mapper=types_mapper)
index_level.name = None
pandas_dtype = _get_index_level_extension_dtype(
col.type, field_name_to_metadata[field_name], types_mapper)
index_level = None
if pandas_dtype is not None:
try:
index_level = pandas_dtype.__from_arrow__(col)
except (TypeError, ValueError, NotImplementedError, pa.ArrowException):
# The metadata no longer describes the column, for example
# because the column was replaced by one of another type
pass
if index_level is None:
index_level = col.to_pandas(types_mapper=types_mapper)
index_level.name = None
result_table = result_table.remove_column(
result_table.schema.get_field_index(field_name)
)
return result_table, index_level, index_name


def _get_index_level_extension_dtype(arrow_type, col_meta, types_mapper=None):
"""
The pandas extension dtype that the pandas metadata stores for an index
level, or None if the level converts as a column without metadata does.

As for the data columns (see _get_extension_dtypes), `types_mapper` and
an Arrow extension type take priority over the metadata.
"""
if types_mapper is not None and types_mapper(arrow_type) is not None:
return None
if isinstance(arrow_type, pa.BaseExtensionType):
return None

dtype = col_meta['numpy_type']
if dtype in _pandas_supported_numpy_types:
return None
try:
pandas_dtype = _pandas_api.pandas_dtype(dtype)
except (TypeError, ValueError):
return None
if not isinstance(pandas_dtype, _pandas_api.extension_dtype):
return None
if isinstance(pandas_dtype, _pandas_api.pd.StringDtype) and not (
pa.types.is_string(arrow_type)
or pa.types.is_large_string(arrow_type)
or pa.types.is_string_view(arrow_type)
):
# A dictionary converts to categorical, and any other type is not
# the strings that the metadata describes
return None
if not hasattr(pandas_dtype, "__from_arrow__"):
return None
return pandas_dtype


def _backwards_compatible_index_name(raw_name, logical_name):
"""Compute the name of an index column that is compatible with older
versions of :mod:`pyarrow`.
Expand Down
53 changes: 53 additions & 0 deletions python/pyarrow/tests/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4618,6 +4618,59 @@ def test_to_pandas_types_mapper_index(index):
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize(
("values", "dtype"),
[
([1, None, 3], "Int64"),
([2**53 + 1, None, 3], "Int64"),
([1, None, 3], "UInt8"),
([1.5, None, 3.0], "Float64"),
([True, None, False], "boolean"),
(["a", None, "c"], "string"),
([1, None, 3], "int64[pyarrow]"),
([1, 2, 3], "int64[pyarrow]"),
],
)
def test_to_pandas_index_extension_dtype(values, dtype):
# GH-55677
index = pd.Index(pd.array(values, dtype=dtype), name="idx")
df = pd.DataFrame({"a": [1, 2, 3]}, index=index)

result = pa.Table.from_pandas(df).to_pandas()
tm.assert_frame_equal(result, df)


def test_to_pandas_multiindex_extension_dtype():
# GH-55677
index = pd.MultiIndex.from_arrays(
[
pd.array([1, None, 3], dtype="Int64"),
["x", "y", "z"],
pd.array([True, False, None], dtype="boolean"),
],
names=["a", "b", "c"],
)
df = pd.DataFrame({"d": [1, 2, 3]}, index=index)

result = pa.Table.from_pandas(df).to_pandas()
tm.assert_frame_equal(result, df)


@pytest.mark.parametrize("dtype", ["Int64", "string"])
def test_to_pandas_index_stale_extension_dtype_metadata(dtype):
# GH-55677: the metadata of a replaced index column is not applied
values = {"Int64": [1, 2], "string": ["x", "y"]}[dtype]
replacement = {"Int64": pa.array(["x", "y"]), "string": pa.array([1, 2])}[dtype]
df = pd.DataFrame(
{"a": [1, 2]}, index=pd.Index(pd.array(values, dtype=dtype), name="idx"))
table = pa.Table.from_pandas(df)
table = table.set_column(
table.schema.get_field_index("idx"), "idx", replacement)

result = table.to_pandas()
assert result.index.tolist() == replacement.to_pylist()


def test_array_to_pandas_types_mapper():
# https://issues.apache.org/jira/browse/ARROW-9664
data = pa.array([1, 2, 3], pa.int64())
Expand Down