将数组的元素通过索引数组求和为 numpy 中的较小数组

RRR*_*RRR 0 python arrays numpy

我有一个包含 N 个 float 类型元素的数组,称为a. 我还有一个包含 N 个元素的数组,称为b. b的元素都是范围内的无符号整数[0, M-1]。我想获得一个大小为 M 的浮点数组,称为c. c只是通过对落入a同一个 bin 中的元素进行求和来“减少”,在 中定义b

基本上这个操作:

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.array([3, 3, 0, 3, 2, 1, 2, 1, 2, 2])
c = ?(a, b)
Run Code Online (Sandbox Code Playgroud)

我想c = [2, 5+7, 4+6+8+9, 0+1+3] = [2, 12, 27, 4]

那么,这个操作的名称是什么?我怎样才能在 numpy 中做到这一点?

小智 5

您可以使用numpy.bincount来完成此操作。

import numpy as np

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.array([3, 3, 0, 3, 2, 1, 2, 1, 2, 2])

c = np.bincount(b,  weights=a)
print(c)

------------------

[ 2. 12. 27.  4.]
Run Code Online (Sandbox Code Playgroud)