Skip to content

Commit 89c4b0e

Browse files
committed
Fix reindex on Dataset from MultiIndex DataFrame with RuntimeError (#10347)
1 parent 34efef2 commit 89c4b0e

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

xarray/structure/alignment.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,9 @@ def _normalize_indexes(
120120
)
121121
data: T_DuckArray = as_compatible_data(idx)
122122
pd_idx = safe_cast_to_index(data)
123-
pd_idx.name = k
123+
if pd_idx.name != k:
124+
pd_idx = pd_idx.copy()
125+
pd_idx.name = k
124126
if isinstance(pd_idx, pd.MultiIndex):
125127
idx = PandasMultiIndex(pd_idx, k)
126128
else:

xarray/tests/test_dataset.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7894,3 +7894,17 @@ def test_transpose_error() -> None:
78947894
),
78957895
):
78967896
ds.transpose(["y", "x"]) # type: ignore[arg-type]
7897+
7898+
7899+
def test_reindex_with_multiindex_level() -> None:
7900+
# test for https://github.com/pydata/xarray/issues/10347
7901+
mindex = pd.MultiIndex.from_product(
7902+
[[100, 200, 300], [1, 2, 3, 4]], names=["x", "y"]
7903+
)
7904+
y_idx = PandasIndex(mindex.levels[1], "y")
7905+
7906+
ds1 = xr.Dataset(coords={"y": [1, 2, 3]})
7907+
ds2 = xr.Dataset(coords=xr.Coordinates.from_xindex(y_idx))
7908+
7909+
actual = ds1.reindex(y=ds2.y)
7910+
assert_identical(actual, ds2)

0 commit comments

Comments
 (0)