问题
I'm trying to join a set of values from one DataArray
, to another. They should join based on a non-dimension coordinate of the first. I think this should be easy but I can't seem to work it out.
The first array:
In [4]: primary=xr.DataArray(np.random.rand(4), dims=list('a'))
...: primary.coords['group'] = (('a',), [0,0,1,1])
...: primary
...:
Out[4]:
<xarray.DataArray (a: 4)>
array([ 0.27772841, 0.06126117, 0.51753086, 0.35994987])
Coordinates:
* a (a) int64 0 1 2 3
group (a) int64 0 0 1 1
The second array:
In [5]: secondary=xr.DataArray(np.random.rand(2), dims=['group'], coords={'group': [0,1]})
...: secondary
...:
Out[5]:
<xarray.DataArray (group: 2)>
array([ 0.75944366, 0.90325489])
Coordinates:
* group (group) int64 0 1
How can I do primary - secondary
such that the arrays are joined along the group
dimension?
Thanks
回答1:
You need to groupby
the first but not apply an aggregation to it:
In [6]: primary.groupby('group') - secondary
Out[6]:
<xarray.DataArray (a: 4)>
array([-0.48171525, -0.69818249, -0.38572403, -0.54330502])
Coordinates:
* a (a) int64 0 1 2 3
group (a) int64 0 0 1 1
来源:https://stackoverflow.com/questions/40229722/join-along-a-non-coordinate-dimension-in-xarray