Skip to content

Commit 4d0300e

Browse files
csernazskmuehlbauerbenbovy
authored
Fix reindex on Dataset from MultiIndex DataFrame with RuntimeError (#10381)
* Fix reindex on Dataset from MultiIndex DataFrame with RuntimeError (#10347) * move test into test dataset class --------- Co-authored-by: Kai Mühlbauer <[email protected]> Co-authored-by: Benoit Bovy <[email protected]>
1 parent c19aa4f commit 4d0300e

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-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: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2369,6 +2369,19 @@ def test_reindex_str_dtype(self, dtype) -> None:
23692369
assert_identical(expected, actual)
23702370
assert actual.x.dtype == expected.x.dtype
23712371

2372+
def test_reindex_with_multiindex_level(self) -> None:
2373+
# test for https://github.com/pydata/xarray/issues/10347
2374+
mindex = pd.MultiIndex.from_product(
2375+
[[100, 200, 300], [1, 2, 3, 4]], names=["x", "y"]
2376+
)
2377+
y_idx = PandasIndex(mindex.levels[1], "y")
2378+
2379+
ds1 = xr.Dataset(coords={"y": [1, 2, 3]})
2380+
ds2 = xr.Dataset(coords=xr.Coordinates.from_xindex(y_idx))
2381+
2382+
actual = ds1.reindex(y=ds2.y)
2383+
assert_identical(actual, ds2)
2384+
23722385
@pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0, {"foo": 2, "bar": 1}])
23732386
def test_align_fill_value(self, fill_value) -> None:
23742387
x = Dataset({"foo": DataArray([1, 2], dims=["x"], coords={"x": [1, 2]})})

0 commit comments

Comments
 (0)