连续在numpy数组中添加值,而无需循环 [英] Add values in numpy array successively, without looping

查看:383
本文介绍了连续在numpy数组中添加值,而无需循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许以前有人问过,但是我找不到. 有时我有一个索引I,我想从另一个数组开始依次将这个索引相应地添加到一个numpy数组中.例如:

Maybe has been asked before, but I can't find it. Sometimes I have an index I, and I want to add successively accordingly to this index to an numpy array, from another array. For example:

A = np.array([1,2,3])
B = np.array([10,20,30])
I = np.array([0,1,1])
for i in range(len(I)):
    A[I[i]] += B[i]
print(A)

打印期望的(正确的)值:

prints the expected (correct) value:

[11 52  3]

同时

A[I] += B
print(A)

得出预期的(错误的)答案

results in the expected (wrong) answer

[11 32  3].

有没有办法以向量化的方式做我想做的事而没有循环? 如果没有,那是最快的方法?

Is there any way to do what I want in a vectorized way, without the loop? If not, which is the fastest way to do this?

推荐答案

使用numpy.add.at:

>>> import numpy as np
>>> A = np.array([1,2,3])
>>> B = np.array([10,20,30])
>>> I = np.array([0,1,1])
>>> 
>>> np.add.at(A, I, B)
>>> A
array([11, 52,  3])

或者,np.bincount:

>>> A = np.array([1,2,3])
>>> B = np.array([10,20,30])
>>> I = np.array([0,1,1])
>>> 
>>> A += np.bincount(I, B, minlength=A.size).astype(int)
>>> A
array([11, 52,  3])

哪个更快?

视情况而定.在这个具体示例中,add.at似乎要快一些,大概是因为我们需要在bincount解决方案中转换类型.

Depends. In this concrete example add.at seems marginally faster, presumably because we need to convert types in the bincount solution.

如果OTOH ABfloat dtype,则bincount会更快.

If OTOH A and B were float dtype then bincount would be faster.

这篇关于连续在numpy数组中添加值,而无需循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆