+1 尽管每个索引元素被多次引用,但每个元素只出现一次。
a = np.arange(12).reshape((3, 4))
b = a.copy()
print(a)
---
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
a[1, [0, 2, 0, 2, 0]] += 1 # a[1][0] referenced 3 times and a[1][2] 2 times
print(a-b)
---
[[0 0 0 0]
[1 0 1 0] # <--- +1 occurs only once for a[1][0] and a[1][2]
[0 0 0 0]]
Run Code Online (Sandbox Code Playgroud)
有没有办法以一种麻木的本机方式创建一种像下面这样的累积加法?
# Result a
[[ 0 1 2 3]
[ 7 5 8 7] <--- +1 three times on a[1][0] and twice on a[1][2]
[ 8 9 10 11]]
# a-b
[[0 0 0 0]
[3 0 2 0] # <--- +3 for a[1][0] and +2 for a[1][2]
[0 0 0 0]]
Run Code Online (Sandbox Code Playgroud)
一种方式可以是reduce-like,类似于map/reduce word计数,但想知道是否有原生的numpy方式。
你要找的是numpy.ufunc.at. 以下是您如何在您的情况下使用它:
np.add.at(a, (1, [0, 2, 0, 2, 0]), 1)
print(a - b)
# [[0 0 0 0]
# [3 0 2 0]
# [0 0 0 0]]
Run Code Online (Sandbox Code Playgroud)
从文档:
对由 'indices' 指定的元素对操作数 'a' 执行无缓冲就地操作。对于加法 ufunc,此方法等价于
a[indices] += b,不同之处在于对索引不止一次的元素累加结果。例如,a[[0,0]] += 1由于缓冲,只会增加第一个元素一次,而add.at(a, [0,0], 1)会将第一个元素增加两次。
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |