Skip to content

Fix reindex on Dataset from MultiIndex DataFrame with RuntimeError #10381

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion xarray/structure/alignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ def _normalize_indexes(
)
data: T_DuckArray = as_compatible_data(idx)
pd_idx = safe_cast_to_index(data)
pd_idx.name = k
if pd_idx.name != k:
pd_idx = pd_idx.copy()
pd_idx.name = k
if isinstance(pd_idx, pd.MultiIndex):
idx = PandasMultiIndex(pd_idx, k)
else:
Expand Down
14 changes: 14 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7894,3 +7894,17 @@ def test_transpose_error() -> None:
),
):
ds.transpose(["y", "x"]) # type: ignore[arg-type]


def test_reindex_with_multiindex_level() -> None:
# test for https://github.com/pydata/xarray/issues/10347
mindex = pd.MultiIndex.from_product(
[[100, 200, 300], [1, 2, 3, 4]], names=["x", "y"]
)
y_idx = PandasIndex(mindex.levels[1], "y")

ds1 = xr.Dataset(coords={"y": [1, 2, 3]})
ds2 = xr.Dataset(coords=xr.Coordinates.from_xindex(y_idx))

actual = ds1.reindex(y=ds2.y)
assert_identical(actual, ds2)
Loading