重复numpy操作的预期行为

时间:2016-06-22 10:32:10

标签: python arrays numpy indices in-place

我在寻找numpy数组上重复操作的问题时找到了这个答案:Increment Numpy multi-d array with repeated indices。我现在的问题是,为什么会出现这种行为。

import numpy as np
t = np.eye(4)

t[[0,0,1],[0,0,1]]

导致

array([1.,1.,1.])

所以不应该

t[[0,0,1],[0,0,1]]+=1 

导致

[[3,0,0,0],
 [0,2,0,0],
 [0,0,1,0],
 [0,0,0,1]]

1 个答案:

答案 0 :(得分:1)

请参阅documentation以索引数组以及基本索引和高级索引之间的区别。

t[[0,0,1],[0,0,1]]属于高级索引类别,如文档中所述:

  

高级索引始终返回数据的副本(与返回视图的基本切片形成对比)。

在第一次增量之前评估副本,如预期的那样,

import numpy as np
t = np.eye(4)
t[[0,0,1],[0,0,1]] += 1
print(t)

打印:

[[ 2.  0.  0.  0.]
 [ 0.  2.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

根据上述评论,使用numpy.ufunc.atnumpy.add.at来解决此问题。