使用数组作为索引增加numpy数组元素 [英] Increase numpy array elements using array as index

查看:62
本文介绍了使用数组作为索引增加numpy数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用另一个数组b来指示要更新的A元素的索引,从而有效地更新numpy数组A的某些元素.但是b可以包含被忽略的重复项,而我希望将其考虑在内.我想避免循环b.为了说明这一点:

I am trying to efficiently update some elements of a numpy array A, using another array b to indicate the indexes of the elements of A to be updated. However b can contain duplicates which are ignored whereas I would like to be taken into account. I would like to avoid for looping b. To illustrate it:

>>> A = np.arange(10).reshape(2,5)
>>> A[0, np.array([1,1,1,2])] += 1
>>> A
array([[0, 2, 3, 3, 4],
       [5, 6, 7, 8, 9]])

我希望输出为:

array([[0, 3, 3, 3, 4],
       [5, 6, 7, 8, 9]])

有什么想法吗?

推荐答案

要正确处理重复的索引,您需要使用np.add.at而不是+=.因此,要更新A的第一行,最简单的方法可能是执行以下操作:

To correctly handle the duplicate indices, you'll need to use np.add.at instead of +=. Therefore to update the first row of A, the simplest way would probably be to do the following:

>>> np.add.at(A[0], [1,1,1,2], 1)
>>> A
array([[0, 4, 3, 3, 4],
       [5, 6, 7, 8, 9]])

ufunc.at方法的文档可以在此处.

这篇关于使用数组作为索引增加numpy数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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