diff --git a/python/pyarrow/pandas_compat.py b/python/pyarrow/pandas_compat.py index 4ff587b702b..d4d0d45a6ed 100644 --- a/python/pyarrow/pandas_compat.py +++ b/python/pyarrow/pandas_compat.py @@ -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`. diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 1f09a9247e6..fd5988521b5 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -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())