Skip to content

Commit 2b38adc

Browse files
authored
Cast PandasIndex to pd.(Multi)Index (#5385)
* fastpath cast Xarray's PandasIndex to pd.Index Also make sure that a multi-index with one unique level are not cast to a simple pd.Index * update tests * [skip-ci] update what's new
1 parent 2a3965c commit 2b38adc

File tree

3 files changed

+8
-0
lines changed

3 files changed

+8
-0
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ Bug fixes
4444
:py:class:`CFTimeIndex` and upcoming pandas version 1.3.0 (:issue:`5356`,
4545
:pull:`5359`).
4646
By `Spencer Clark <https://github.com/spencerkclark>`_.
47+
- Fix 1-level multi-index incorrectly converted to single index (:issue:`5384`,
48+
:pull:`5385`).
49+
By `Benoit Bovy <https://github.com/benbovy>`_.
4750

4851

4952
Documentation

xarray/core/utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ def safe_cast_to_index(array: Any) -> pd.Index:
107107
index = array
108108
elif hasattr(array, "to_index"):
109109
index = array.to_index()
110+
elif hasattr(array, "to_pandas_index"):
111+
index = array.to_pandas_index()
110112
else:
111113
kwargs = {}
112114
if hasattr(array, "dtype") and array.dtype.kind == "O":

xarray/tests/test_utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
from xarray.coding.cftimeindex import CFTimeIndex
99
from xarray.core import duck_array_ops, utils
10+
from xarray.core.indexes import PandasIndex
1011
from xarray.core.utils import either_dict_or_kwargs
1112

1213
from . import assert_array_equal, requires_cftime, requires_dask
@@ -28,11 +29,13 @@ def test_safe_cast_to_index():
2829
dates = pd.date_range("2000-01-01", periods=10)
2930
x = np.arange(5)
3031
td = x * np.timedelta64(1, "D")
32+
midx = pd.MultiIndex.from_tuples([(0,)], names=["a"])
3133
for expected, array in [
3234
(dates, dates.values),
3335
(pd.Index(x, dtype=object), x.astype(object)),
3436
(pd.Index(td), td),
3537
(pd.Index(td, dtype=object), td.astype(object)),
38+
(midx, PandasIndex(midx)),
3639
]:
3740
actual = utils.safe_cast_to_index(array)
3841
assert_array_equal(expected, actual)

0 commit comments

Comments
 (0)