harbor run -t openthoughts/tasktrove-exp-rpt-issue-issue-1184harbor download openthoughts/tasktrove-exp-rpt-issue-issue-1184SELF-CONTAINED TASK: Fix selection from MultiIndex in xarray (dataArray.sel should respect MultiIndex after set_index)
# ... (other imports and code)
from .dataset import Dataset, merge_indexes, split_indexes
# ...
class DataArray:
# ...
def set_index(self, indexes, append=None, inplace=False, **indexes_kwargs):
"""
DataArray.set_index
"""
_check_inplace(inplace)
indexes = either_dict_or_kwargs(indexes, indexes_kwargs, "set_index")
coords, _ = merge_indexes(indexes, self._coords, set(), append=append)
return self._replace(coords=coords)
# ... (imports and code)
def merge_indexes(
indexes,
variables,
coord_names,
append=False,
):
"""
Merge given indexes into the existing Variables/Coords.
- indexes: mapping from new index name to one or more existing variable names
- variables: current variables (including coordinates)
- coord_names: current coordinate names
- append: whether to append (used in set_index)
"""
vars_to_replace: Dict[Hashable, Variable] = {}
vars_to_remove: List[Hashable] = []
error_msg = "{} is not the name of an existing variable."
for dim, var_names in indexes.items():
if dim not in variables:
raise KeyError(error_msg.format(dim))
if not isinstance(var_names, (list, tuple)):
var_names = [var_names]
if len(var_names) == 0:
raise ValueError("empty group in set_index")
if len(var_names) == 1:
idx = IndexVariable(dim, variables[var_names[0]].values)
else:
# MultiIndex
levels = []
codes = []
names = var_names
for n in var_names:
var = variables[n]
levels.append(var.values if not isinstance(var, IndexVariable) else var._data)
codes.append(range(len(var)))
idx = pd.MultiIndex(levels, codes, names=names)
for n in var_names:
dims_to_replace[n] = dim
vars_to_replace[dim] = IndexVariable(dim, idx)
vars_to_remove.extend(var_names)
new_variables = {k: v for k, v in variables.items() if k not in vars_to_remove}
new_variables.update(vars_to_replace)
new_coord_names = coord_names | set(vars_to_replace)
new_coord_names -= set(vars_to_remove)
return new_variables, new_coord_names
Example manual check snippet to include in your testing area (not in the patch itself):
Example check code you can run locally after implementing the fix:
import xarray as xr
import numpy as np
da = xr.DataArray([0, 1], dims=['x'], coords={'x': [0, 1], 'y': 'a'})
db = xr.DataArray([2, 3], dims=['x'], coords={'x': [0, 1], 'y': 'b'})
data = xr.concat([da, db], dim='x').set_index(xy=['x', 'y'])
out = data.sel(y='a')
print(out)
# Expected: <xarray.DataArray (x: 2)> with values [0, 1] and coords x: [0, 1]