diff --git a/doc/whats-new.rst b/doc/whats-new.rst index b957ed4bab2..fb96ed6293c 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -44,6 +44,9 @@ Bug fixes :py:class:`CFTimeIndex` and upcoming pandas version 1.3.0 (:issue:`5356`, :pull:`5359`). By `Spencer Clark `_. +- Fix 1-level multi-index incorrectly converted to single index (:issue:`5384`, + :pull:`5385`). + By `Benoit Bovy `_. Documentation diff --git a/xarray/core/utils.py b/xarray/core/utils.py index aa51366f588..3a9f418063d 100644 --- a/xarray/core/utils.py +++ b/xarray/core/utils.py @@ -107,6 +107,8 @@ def safe_cast_to_index(array: Any) -> pd.Index: index = array elif hasattr(array, "to_index"): index = array.to_index() + elif hasattr(array, "to_pandas_index"): + index = array.to_pandas_index() else: kwargs = {} if hasattr(array, "dtype") and array.dtype.kind == "O": diff --git a/xarray/tests/test_utils.py b/xarray/tests/test_utils.py index 8b5bcbedb7d..483fa723058 100644 --- a/xarray/tests/test_utils.py +++ b/xarray/tests/test_utils.py @@ -7,6 +7,7 @@ from xarray.coding.cftimeindex import CFTimeIndex from xarray.core import duck_array_ops, utils +from xarray.core.indexes import PandasIndex from xarray.core.utils import either_dict_or_kwargs from . import assert_array_equal, requires_cftime, requires_dask @@ -28,11 +29,13 @@ def test_safe_cast_to_index(): dates = pd.date_range("2000-01-01", periods=10) x = np.arange(5) td = x * np.timedelta64(1, "D") + midx = pd.MultiIndex.from_tuples([(0,)], names=["a"]) for expected, array in [ (dates, dates.values), (pd.Index(x, dtype=object), x.astype(object)), (pd.Index(td), td), (pd.Index(td, dtype=object), td.astype(object)), + (midx, PandasIndex(midx)), ]: actual = utils.safe_cast_to_index(array) assert_array_equal(expected, actual)