Join along a non-coordinate dimension in xarray

怎甘沉沦 提交于 2019-12-24 06:00:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!