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

标签 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]]

?

最佳答案

参见 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.atnumpy.add.at 来解决这个问题。

关于python - 重复 numpy 操作的预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37965407/

相关文章:

javascript - Async.map - 让它忽略错误,并处理整个列表

python - 将子字符串的多个实例替换为列表中的项目

python - Python scipy/numpy/pandas 中时间序列的分层聚类?

Python Django - 通过 ListView 更新 booleanField

java - 从二维整数数组中查找最常见的值

python - 使用 PyCapture2 读取 MONO 16 位图像

python - 当矩阵中的行多 10 倍时,为什么 np.dot 不会(至少)长 10 倍

python - 将我的查询结果放入字符串中以便可以打印

java - 如果标签相同则合并文件的时间戳

python - flask celery redis 没有返回值