是否有numpy中的MATLAB accumarray等效项? [英] Is there a MATLAB accumarray equivalent in numpy?

查看:97
本文介绍了是否有numpy中的MATLAB accumarray等效项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找针对MATLAB accumarray 在numpy中. accumarray累积属于同一索引的数组元素.一个例子:

I'm looking for a fast solution to MATLAB's accumarray in numpy. The accumarray accumulates the elements of an array which belong to the same index. An example:

a = np.arange(1,11)
# array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
accmap = np.array([0,1,0,0,0,1,1,2,2,1])

结果应为

array([13, 25, 17])

我到目前为止所做的事情: 我已经尝试过此处的食谱中的accum函数,该函数可以正常运行,但速度较慢. /p>

What I've done so far: I've tried the accum function in the recipe here which works fine but is slow.

accmap = np.repeat(np.arange(1000), 20)
a = np.random.randn(accmap.size)
%timeit accum(accmap, a, np.sum)
# 1 loops, best of 3: 293 ms per loop

然后我尝试使用解决方案这里应该可以更快地运行,但是不能正常运行:

Then I tried to use the solution here which is supposed to work faster but it doesn't work correctly:

accum_np(accmap, a)
# array([  1.,   2.,  12.,  13.,  17.,  10.])

是否有内置的numpy函数可以进行这样的累加?或其他任何建议?

Is there a built-in numpy function that can do accumulation like this? Or any other recommendations?

推荐答案

使用 weights可选参数.在您的示例中,您将执行以下操作:

Use np.bincount with the weights optional argument. In your example you would do:

np.bincount(accmap, weights=a)

这篇关于是否有numpy中的MATLAB accumarray等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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