diff --git a/python/pyarrow/pandas_compat.py b/python/pyarrow/pandas_compat.py index 4ff587b702b..08459022203 100644 --- a/python/pyarrow/pandas_compat.py +++ b/python/pyarrow/pandas_compat.py @@ -1048,8 +1048,36 @@ 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 + # restore the pandas extension dtype (e.g. Int64) stored in the metadata, + # unless types_mapper handles this type (as for data columns) + numpy_type = field_name_to_metadata[field_name]['numpy_type'] + pandas_dtype = None + if ( + numpy_type not in _pandas_supported_numpy_types + and not pa.types.is_dictionary(col.type) + and (types_mapper is None or types_mapper(col.type) is None) + ): + pandas_dtype = _pandas_api.pandas_dtype(numpy_type) + if isinstance(pandas_dtype, _pandas_api.pd.StringDtype) and not ( + pa.types.is_string(col.type) + or pa.types.is_large_string(col.type) + or pa.types.is_string_view(col.type) + or pa.types.is_binary(col.type) + or pa.types.is_large_binary(col.type) + or pa.types.is_binary_view(col.type) + or pa.types.is_null(col.type) + ): + # the index level was replaced by one of another type after the + # metadata was written + pandas_dtype = None + if ( + isinstance(pandas_dtype, _pandas_api.extension_dtype) + and hasattr(pandas_dtype, "__from_arrow__") + ): + index_level = _pandas_api.pd.Series(pandas_dtype.__from_arrow__(col)) + else: + 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) ) diff --git a/python/pyarrow/tests/test_pandas.py b/python/pyarrow/tests/test_pandas.py index 1f09a9247e6..1c330e6b22f 100644 --- a/python/pyarrow/tests/test_pandas.py +++ b/python/pyarrow/tests/test_pandas.py @@ -4602,6 +4602,42 @@ def test_roundtrip_empty_table_with_extension_dtype_index(): tm.assert_index_equal(table.to_pandas().index, df.index) +@pytest.mark.parametrize("values, dtype", [ + ([1, None, 3], "Int64"), + ([1.5, None, 3.5], "Float32"), + ([True, False, None], "boolean"), + (["a", None, "c"], "string"), + ([1, 2, 3], "UInt8"), + ([1, None, 3], "int64[pyarrow]"), +]) +def test_roundtrip_index_with_extension_dtype(values, dtype): + 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) + + mi = pd.MultiIndex.from_arrays([index, ["x", "y", "z"]], names=["i", "j"]) + df = pd.DataFrame({"a": [1, 2, 3]}, index=mi) + result = pa.Table.from_pandas(df).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.parametrize("dtype", [None, "string"]) +@pytest.mark.parametrize( + "new_column", + [pa.array([7, 8, 9]), pa.array([1.5, 2.5, 3.5]), pa.array([True, False, None])], +) +def test_to_pandas_replaced_string_index_level_with_stale_metadata(new_column, + dtype): + # The pandas metadata still describes the replaced index level as a + # string column; its values must not be converted to strings. + index = pd.Index(pd.Series(["x", "y", "z"], dtype=dtype), name="idx") + df = pd.DataFrame({"a": [1, 2, 3]}, index=index) + table = pa.Table.from_pandas(df).set_column(1, "idx", new_column) + result = table.to_pandas() + tm.assert_index_equal(result.index, pd.Index(new_column.to_pandas(), name="idx")) + + @pytest.mark.parametrize("index", ["a", ["a", "b"]]) def test_to_pandas_types_mapper_index(index): df = pd.DataFrame(