Skip to content

Commit 316a59b

Browse files
DHRUVA KUMAR KAUSHALDHRUVA KUMAR KAUSHAL
authored andcommitted
Allow custom indexes to create new variables
1 parent a8de733 commit 316a59b

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

xarray/core/dataset.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4875,6 +4875,10 @@ def set_xindex(
48754875
"""Set a new, Xarray-compatible index from one or more existing
48764876
coordinate(s).
48774877
4878+
All variables returned by the index's ``create_variables()`` method
4879+
will be added to the dataset, including any additional variables
4880+
beyond the original coordinate names.
4881+
48784882
Parameters
48794883
----------
48804884
coord_names : str or list
@@ -4891,6 +4895,9 @@ def set_xindex(
48914895
-------
48924896
obj : Dataset
48934897
Another dataset, with this dataset's data and with a new index.
4898+
The index will be associated with the coordinates specified in
4899+
``coord_names``. Any additional variables returned by the index's
4900+
``create_variables()`` method will also be added to the dataset.
48944901
48954902
"""
48964903
# the Sequence check is required for mypy
@@ -4947,10 +4954,13 @@ def set_xindex(
49474954
variables = self._variables.copy()
49484955
indexes = self._indexes.copy()
49494956

4950-
name = list(coord_names).pop()
4951-
if name in new_coord_vars:
4952-
variables[name] = new_coord_vars[name]
4953-
indexes[name] = index
4957+
# Add ALL variables returned by create_variables()
4958+
for name, var in new_coord_vars.items():
4959+
variables[name] = var
4960+
4961+
# Set index only for the original coordinate name
4962+
coord_name = list(coord_names).pop()
4963+
indexes[coord_name] = index
49544964
else:
49554965
# reorder variables and indexes so that coordinates having the same
49564966
# index are next to each other
@@ -4964,11 +4974,12 @@ def set_xindex(
49644974
if name not in coord_names:
49654975
indexes[name] = idx
49664976

4977+
# Add ALL variables returned by create_variables()
4978+
for name, var in new_coord_vars.items():
4979+
variables[name] = var
4980+
4981+
# Set index for all original coordinate names
49674982
for name in coord_names:
4968-
try:
4969-
variables[name] = new_coord_vars[name]
4970-
except KeyError:
4971-
variables[name] = self._variables[name]
49724983
indexes[name] = index
49734984

49744985
return self._replace(

0 commit comments

Comments
 (0)