Skip to content

DataArray.set_index throws error on documented input #3176

@gwgundersen

Description

@gwgundersen

Problem Description

Docs for DataArray.set_index describe the main indexes argument as:

Mapping from names matching dimensions and values given by (lists of) the names of existing coordinates or variables to set as new (multi-)index.

This suggests that one can set a DataArray instance's coordinates by passing in a dimension and a list-like object of coordinates.

MCVE

In [1]: import numpy as np

In [2]: import xarray as xr

In [3]: arr = xr.DataArray(data=np.ones((2, 3)), dims=['x', 'y'])

In [4]: arr.dims
Out[4]: ('x', 'y')

In [5]: arr.set_index({'x': range(2)})
KeyError   
...
    144         for n in var_names:
--> 145             var = variables[n]
    146             if (current_index_variable is not None and
    147                     var.dims != current_index_variable.dims):

KeyError: 0

At first, I thought it might be because coords and _coords were not being set in this case:

In [18]: arr.coords
Out[18]: 
Coordinates:
    *empty*

In [19]: arr._coords
Out[19]: OrderedDict()

but even if I set the coordinates first and then try to re-index, it fails:

In [20]: arr = xr.DataArray(data=np.ones((2, 3)), dims=['x', 'y'], coords={'x': range(2), 'y': range(3)})
In [21]: arr.set_index({'x': ['a', 'b', 'c']})
...
    144         for n in var_names:
--> 145             var = variables[n]
    146             if (current_index_variable is not None and
    147                     var.dims != current_index_variable.dims):

Expected Output

I expect my MCVE to work based on the documentation.

Problem Solution

My guess is that the issue is Xarray is using the merge_indexes function (see here) from the Dataset module, and there is no concept of a variable in a DataArray.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions