Skip to content

Convert an existing xarray dimension into a MultiIndex #1331

@shoyer

Description

@shoyer

Suppose I have two xarray Datasets, each defined along the 'x' axis:

ds1 = xarray.Dataset({'foo': (('x',), [1, 2, 3])}, {'x': [1, 2, 3], 'y': 'a'})
ds2 = xarray.Dataset({'foo': (('x',), [4, 5, 6])}, {'x': [1, 2, 3], 'y': 'b'})
<xarray.Dataset>
Dimensions:  (x: 3)
Coordinates:
    y        |S1 'a'
  * x        (x) int64 1 2 3
Data variables:
    foo      (x) int64 1 2 3

Now I want to stack them along a new MultiIndex 'yx' that consists of y and x levels:

desired = xarray.Dataset({'foo': (('yx',), [1, 2, 3, 4, 5, 6])},
                         {'yx': pandas.MultiIndex.from_product([['a', 'b'], [1, 2, 3]], names=['y', 'x'])})
<xarray.Dataset>
Dimensions:  (yx: 6)
Coordinates:
  * yx       (yx) MultiIndex
  - y        (yx) object 'a' 'a' 'a' 'b' 'b' 'b'
  - x        (yx) int64 1 2 3 1 2 3
Data variables:
    foo      (yx) int64 1 2 3 4 5 6

How can this be achieved with the minimum effort? What is the missing utility function that we need? I attempted to use set_index and swap_dims but so far have been unsuccessful.

@benbovy any ideas? I think something similar may have come up when we were discussing your set_index PR.

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