我想将二维数组的元素“移动”到存储在另外 2 个数组中的新坐标。我希望将其自动化,因为实际上我的数组很大 (400x200x100)。 有些值不会找到他的坐标,也不会被使用, 其中一些坐标被屏蔽了,我在下面的示例中使用值 0 表示了这一点。如果坐标被屏蔽,则不会使用我要重新洗牌的数组中的元素。
import numpy as np
#My new coordinates in X and Y directions
mx = np.array([[ 1., 2., 3., 4., 0.],
[ 1., 2., 3., 4., 0.],
[ 1., 2., 3., 4., 0.],
[ 1., 2., 3., 4., 0.],
[ 1., 2., 3., 4., 0.]])
my = np.array([[ 0., 2., 2., 2., 2.],
[ 0., 3., 3., 3., 3.],
[ 0., 4., 4., 4., 4.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
#The array with values to move
IRtest = np.array([[-0.07383495, -0.08606554, -0.08480594, -0.08099556, -0.08218414],
[-0.07866761, -0.08373 , -0.08253587, -0.08106102, -0.08220205],
[-0.07727436, -0.08271511, -0.0807254 , -0.07832416, -0.08021686],
[-0.07612349, -0.08190446, -0.07996929, -0.07842754, -0.08024891],
[-0.07488144, -0.08150557, -0.08038229, -0.07895656, -0.07997815]])
#Creation of zeros array to get new array
b = np.zeros((5,5))
# I tried this but it doesn't work...
for i in range(IRtest.shape[0]):
for j in range(IRtest.shape[1]):
b[my[i,j], mx[i,j]] = IRtest[i,j]
plt.imshow(b)
plt.colorbar()
plt.show()
所以预期的数组看起来像:
array_expected = np.array([[-0.08271511, -0.0807254 , -0.07832416, -0.08021686, 0],
[-0.08190446, -0.07996929, -0.07842754, -0.08024891, 0],
[-0.08150557, -0.08038229, -0.07895656, -0.07997815, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
-----稍后编辑----------------
在这个“方向”上更好:
for i in range(IRtest.shape[0]):
for j in range(IRtest.shape[1]):
b[j, i] = IRtest[my[j,i],mx[j,i]]
我明白了:
array([[-0.08606554, -0.0807254 , -0.07832416, -0.08021686, -0.07727436],
[-0.08606554, -0.07996929, -0.07842754, -0.08024891, -0.07612349],
[-0.08606554, -0.08038229, -0.07895656, -0.07997815, -0.07488144],
[-0.08606554, -0.08480594, -0.08099556, -0.08218414, -0.07383495],
[-0.08606554, -0.08480594, -0.08099556, -0.08218414, -0.07383495]])
所以最后一个问题是处理屏蔽值...
所以我尝试:
mask_mx = np.array([[False, False, False, False, True],
[False, False, False, False, True],
[False, False, False, False, True],
[False, False, False, False, True],
[False, False, False, False, True]], dtype=int)
mask_my = np.array([[True, False, False, False, False],
[True, False, False, False, False],
[True, False, False, False, False],
[True, True, True, True, True],
[True, True, True, True, True]], dtype=int)
mx3 = np.where(mask_mx, 'nan', mx)
my3 = np.where(mask_my, 'nan', my)
for i in range(IRtest.shape[0]):
for j in range(IRtest.shape[1]):
b[j, i] = IRtest[my3[j,i],mx3[j,i]]
但是我得到下面的错误,它不喜欢 'nan' 作为坐标: 以 10 为底的 int() 的无效文字:'nan'
请您参考如下方法:
您可能想使用 -1 作为掩码而不是 0,这样您就可以在 IRtest 中访问 0 索引。
mx = np.array([[ 1., 2., 3., 4., -1.],
[ 1., 2., 3., 4., -1.],
[ 1., 2., 3., 4., -1.],
[ 1., 2., 3., 4., -1.],
[ 1., 2., 3., 4., -1.]])
my = np.array([[ 2., 2., 2., 2., 2.],
[ 3., 3., 3., 3., 3.],
[ 4., 4., 4., 4., 4.],
[ -1., -1., -1., -1., -1.],
[ -1., -1., -1., -1., -1.]])
b = np.zeros_like(IRtest)
for i in range(IRtest.shape[0]):
for j in range(IRtest.shape[1]):
b[j, i] = IRtest[my[j,i],mx[j,i]]*(mx[j,i]!=-1)*(my[j,i]!=-1)
