Skip to content

Commit 5d3ac67

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

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-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_indexes.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,35 @@ def test_reindex_like(self) -> None:
293293
with pytest.raises(ValueError, match=r".*index has duplicate values"):
294294
index3.reindex_like(index2)
295295

296+
def test_reindex_pandas_multiframe(self) -> None:
297+
# test for GH10347
298+
rand1 = np.arange(15)
299+
rand2 = np.arange(12)
300+
301+
data1 = xr.DataArray(
302+
rand1.reshape((5, 3)),
303+
dims=("x", "y"),
304+
coords={"x": [1, 2, 3, 4, 5], "y": [1, 2, 3]},
305+
).to_dataset(name="value")
306+
307+
base1 = xr.DataArray(
308+
rand2.reshape(3, 4),
309+
dims=("x", "y"),
310+
coords={"x": [100, 200, 300], "y": [1, 2, 3, 4]},
311+
).to_dataset(name="base_value")
312+
313+
base2 = xr.Dataset.from_dataframe(
314+
pd.DataFrame(
315+
rand2,
316+
columns=["base_value"],
317+
index=pd.MultiIndex.from_product(
318+
[[100, 200, 300], [1, 2, 3, 4]], names=["x", "y"]
319+
),
320+
)
321+
)
322+
323+
assert data1.reindex(y=base1.y) == data1.reindex(y=base2.y)
324+
296325
def test_rename(self) -> None:
297326
index = PandasIndex(pd.Index([1, 2, 3], name="a"), "x", coord_dtype=np.int32)
298327

0 commit comments

Comments
 (0)