I am trying to get started using Xarray, but having an issue with a specific task: the labels I want to use in one dimension are dependent on another dimension.
Specifically, in the example below, the labels/indices which should be used in the "ti" dimension are dependent on the category in the "regime" dimension.
import numpy as np
import xarray as xr
wd_index = np.arange(40,85,3)
ws_index = np.arange(0,100,5)
ti_indices = {'free':[0.013651005,0.02097709,0.028776308,0.041105852,0.083883279],
'restricted':[0.0243316245,0.037467915,0.04940437,0.055962806,0.065437968],
'closed':[0.042476781,0.055642339,0.064246267,0.078399973,0.120953288]}
values = np.random.rand(3,5,15,20)
array = xr.DataArray(values, dims=['regime','ti','wd','ws'],
coords={'regime':['free','restricted','closed'],
'ti':(['regime', 'ti'],np.array([ti_indices['free'],ti_indices['restricted'],ti_indices['closed']],dtype=object)),
'wd':wd_index,
'ws':ws_index})
check = array.sel({'regime':'free','ws':5,'ti':ti_indices['free'][0]})
This last line returns:
raise KeyError(f"no index found for coordinate {key!r}")
KeyError: "no index found for coordinate 'ti'"
But I haven't yet figured out how to correctly assign the index. I also tried:
xr.DataArray(values, dims=['regime','ti','wd','ws'],
coords={'regime':['free','restricted','closed'],
'ti':(['regime', 'ti'],{'free':ti_indices['free'],
'restricted':ti_indices['restricted'],
'closed':ti_indices['closed']}),
'wd':wd_index,
'ws':ws_index})
but this is apparently not a correct syntax, and returns:
ValueError: Variable 'ti': Could not convert tuple of form (dims, data[, attrs, encoding]): (['regime', 'ti'], {'free': [0.013651005, 0.02097709, 0.028776308, 0.041105852, 0.083883279], 'restricted': [0.0243316245, 0.037467915, 0.04940437, 0.055962806, 0.065437968], 'closed': [0.042476781, 0.055642339, 0.064246267, 0.078399973, 0.120953288]}) to Variable.