如何从 3 个向量(X、Y 和 Z)构建 2D numpy 数组,其中 A[X,Y] += Z?

问题描述 投票:0回答:1

我想从 3 个相同大小的向量创建一个 2D numpy 数组,将其中 2 个作为每个维度的索引,将第三个作为指定值,将其添加到同一位置中保存的向量中。我首先构建了零数组,然后将值指定为 A[X,Y] +=Z。例如:

import numpy as np

X = [0,1,1]

Y = [2,2,2]

Z = [1,2,3]

A = np.zeros([3, 3], dtype=int8)

A[X,Y] +=Z

结果:

A = array([[0, 0, 1],
           [0, 0, 3],
           [0, 0, 0]], dtype=int8)

我期待 A[1,2] = 5 (A[X1,Y1] + A[X2,Y2] = 2+3),但实际上 A[1,2] = 3 (只是保留了最后一个值) 。我怎样才能以numpy的方式解决这个问题?

我得到了Python风格的解决方案,但速度较慢

for i,j,k in zip (X,Y,Z):
    A[i,j]+= k

print (A)

A = array([[0, 0, 1],
       [0, 0, 5],
       [0, 0, 0]], dtype=int8)
numpy-ndarray
1个回答
0
投票

您可以像这样使用

np.add.at
ufunc:

import numpy as np

X = [0, 1, 1]
Y = [2, 2, 2]
Z = [1, 2, 3]

A = np.zeros((3, 3))

np.add.at(A, (X, Y), Z) # Has to be tuple, or it won't work

print(A)

输出:

[[0. 0. 1.]
 [0. 0. 5.]
 [0. 0. 0.]]
© www.soinside.com 2019 - 2024. All rights reserved.