首页 > 解决方案 > Xarray沿相同维度添加(如求和)两行但坐标值不同

问题描述

我使用 xarray 创建了两个具有相同尺寸和坐标的不同 DataArray。但是我想在这些维度之一中添加两个不同的坐标。我正在尝试将坐标“a”添加到维度“x”中的坐标“b”。如果这些是我的矩阵的唯一维度,则有一个简单的解决方法,但如果我有更多维度并且我想保持其他维度的正常 xarray 行为,则更复杂。请参阅下面在最后一行失败的示例。我知道如何在 numpy 中手动修复这个问题,但 xarray 的美妙之处在于我不应该这样做。

xarray 是否允许这种操作的简单解决方案?


import xarray as xr
import numpy as np

# create simple DataArray M and N to show what I would like to do
M = xr.DataArray([1, 2], dims="x",coords={'x':['a','b']})
N = xr.DataArray([3, 4], dims="x",coords={'x':['a','b']})

print(M.sel(x='a')+N.sel(x='b'))  # this will NOT give me the value 
print(M.sel(x='a').values+N.sel(x='b').values) # this will give me the value


# create a more complex DataArray M and N to show what the challenge
m = np.arange(3*2*4)
m = m.reshape(3,2,4)
n = np.arange(4*2*3)
n = n.reshape(4,2,3)
M = xr.DataArray(m, dims=['z1',"x","z2"],coords={'x':['a','b']})
N = xr.DataArray(n, dims=["z2",'x','z1'],coords={'x':['a','b']})

print(M.sel(x='a')+N.sel(x='b'))  # this will NOT give me the value 
print(M.sel(x='a').values+N.sel(x='b').values) # this will result in an error

标签: pythonaddpython-xarray

解决方案


推荐阅读