How to create an xarray from a sparse, denormalized table?

140 Views Asked by At

Say I have the following structured array:

import numpy as np

l, h, w = 6, 5, 5
dtype = [('a', int), ('b', '<U3'), ('data', (float, (h, w)))]
table = np.empty(l, dtype)
table['a'] = [1, 2, 3, 1, 2, 3]
table['b'] = ['foo', 'bar'] * 3
table['data'] = np.random.rand(l, h, w)

My data has shape (6, 5, 5). But really, its shape is (3, 2, 5, 5), but I just have columns a and b denormalized.

Is it possible to create an xarray DataArray directly from this shape (6, 5, 5) by providing columns a and b of length 6 and have xarray figure out the (3, 2, 5, 5) shape? What would coords and dims be?

In reality, table is sparse and has many dimensions, and I'm trying to see if there's any xarray creation machinery I can lean on instead of reshaping table myself.

0

There are 0 best solutions below