Skip to content

Commit abce7dd

Browse files
DHRUVA KUMAR KAUSHALDHRUVA KUMAR KAUSHAL
authored andcommitted
logic update
1 parent 1a734b7 commit abce7dd

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

doc/whats-new.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ Deprecations
2525
Bug fixes
2626
~~~~~~~~~
2727

28+
- :py:meth:`Dataset.set_xindex` now raises a helpful error when a custom index
29+
creates extra variables that don't match the provided coordinate names, instead
30+
of silently ignoring them. The error message suggests using the factory method
31+
pattern with :py:meth:`xarray.Coordinates.from_xindex` and
32+
:py:meth:`Dataset.assign_coords` for advanced use cases (:issue:`10499`).
33+
By `Dhruva Kumar Kaushal <https://github.com/dhruvak001>`_.
2834

2935
Documentation
3036
~~~~~~~~~~~~~

xarray/core/dataset.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4940,6 +4940,20 @@ def set_xindex(
49404940
if isinstance(index, PandasMultiIndex):
49414941
coord_names = [index.dim] + list(coord_names)
49424942

4943+
# Check for extra variables that don't match the coordinate names
4944+
extra_vars = set(new_coord_vars) - set(coord_names)
4945+
if extra_vars:
4946+
extra_vars_str = ", ".join(f"'{name}'" for name in extra_vars)
4947+
coord_names_str = ", ".join(f"'{name}'" for name in coord_names)
4948+
raise ValueError(
4949+
f"The index created extra variables {extra_vars_str} that are not "
4950+
f"in the list of coordinates {coord_names_str}. "
4951+
f"Use a factory method pattern instead:\n"
4952+
f" index = {index_cls.__name__}.from_variables(ds, {list(coord_names)!r})\n"
4953+
f" coords = xr.Coordinates.from_xindex(index)\n"
4954+
f" ds = ds.assign_coords(coords)"
4955+
)
4956+
49434957
variables: dict[Hashable, Variable]
49444958
indexes: dict[Hashable, Index]
49454959

0 commit comments

Comments
 (0)