在numpy中有一个MATLAB的accumarray等价物吗?

2024-10-06 11:19:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个快速解决MATLAB在numpy中的^{}问题的方法。accumarray累加属于同一索引的数组元素。例如:

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])

到目前为止我所做的: 我试过recipe here中的accum函数,它工作得很好,但速度很慢。

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

然后我尝试使用solution here它应该工作得更快,但它不能正确工作:

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

有没有一个内置的numpy函数可以像这样进行累加?或者其他建议?


Tags: 方法函数numpy元素herenprecipe数组