在Numpy Array中累积常量值

时间:2016-04-26 11:18:44

标签: python arrays numpy

我正在尝试将+1加入到numpy数组的某些特定单元格中,但如果没有慢速循环,我找不到任何方法:

coords = np.array([[1,2],[1,2],[1,2],[0,0]])
X      = np.zeros((3,3))

for i,j in coords:
  X[i,j] +=1 

导致:

X = [[ 1.  0.  0.]
     [ 0.  0.  3.]
     [ 0.  0.  0.]]

X[coords[:,0],coords[:,1] += 1返回

X = [[ 1.  0.  0.]
     [ 0.  0.  1.]
     [ 0.  0.  0.]]

任何帮助?

3 个答案:

答案 0 :(得分:4)

numpy.at完全符合这些情况。

In [1]: np.add.at(X,tuple(coords.T),1)

In [2]: X
Out[2]: 
array([[ 1.,  0.,  0.],
       [ 0.,  0.,  3.],
       [ 0.,  0.,  0.]])

答案 1 :(得分:3)

您可以使用np.bincount,就像这样 -

out_shape = (3,3) # Input param

# Get linear indices corresponding to coords with the output array shape.
# These form the IDs for accumulation in the next step.
ids = np.ravel_multi_index(coords.T,out_shape)

# Use bincount to get 1-weighted accumulations. Since bincount assumes 1D
# array, we need to do reshaping before and after for desired output.
out = np.bincount(ids,minlength=np.prod(out_shape)).reshape(out_shape)

如果您尝试分配1s以外的值,则可以使用其他输入参数将权重输入np.bincount

示例运行 -

In [2]: coords
Out[2]: 
array([[1, 2],
       [1, 2],
       [1, 2],
       [0, 0]])

In [3]: out_shape = (3,3) # Input param
   ...: ids = np.ravel_multi_index(coords.T,out_shape)
   ...: out = np.bincount(ids,minlength=np.prod(out_shape)).reshape(out_shape)
   ...: 

In [4]: out
Out[4]: 
array([[1, 0, 0],
       [0, 0, 3],
       [0, 0, 0]], dtype=int64)

答案 2 :(得分:2)

另一个选项是np.histogramdd

bins = [np.arange(d + 1) for d in X.shape]
out, edges = np.histogramdd(coords, bins)

print(out)
# [[ 1.  0.  0.]
#  [ 0.  0.  3.]
#  [ 0.  0.  0.]]