Skip to main content
 首页 » 编程设计

python之重复 numpy 操作的预期行为

2025年04月02日16lidabo

我在寻找对 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]] 

?

请您参考如下方法:

参见 documentation用于索引数组以及基本索引和高级索引之间的区别。

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

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

副本在第一次递增之前被评估,所以正如预期的那样,

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.at 或 numpy.add.at 来解决这个问题。