我在寻找对 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
来解决这个问题。
关于python - 重复 numpy 操作的预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37965407/