繁体   English   中英

NumPy:对一维数组求和,按索引拆分

[英]NumPy: Sum over 1-D array split by index

考虑一维NumPy输入数组和排序索引数组。 目标是获得输入数组a的总和,但由索引数组中定义的索引拆分。

以下是两种方法,但它们都需要慢速 Python 循环。 是否有不需要 Python 循环的纯NumPy版本?

示例

a = np.arange(20) # Input array
idxs = np.array([7, 15, 16]) # Index array

# Goal: Split a at index 7, 15 and 16 and
# compute sum for each partition

# Solution 1:
idxs_ext = np.concatenate(([0], idxs, [a.size]))
results = np.empty(idxs.size + 1)
for i in range(results.size):
    results[i] = a[idxs_ext[i]:idxs_ext[i+1]].sum()

# Solution 2:
result = np.array(
    [a_.sum() for a_ in np.split(a, idxs)]
)

# Result: array([21., 84., 15., 70.])

首先,您可以通过np.split根据您的idxs数组拆分a数组,然后将 function 应用为:

np.stack(np.vectorize(np.sum)(np.array(np.split(a, idxs), dtype=object)))

另一个答案是使用np.add.reduceat在评论中提到的 np.add.reduceat 并且更快:

np.add.reduceat(a, np.insert(idxs, 0, 0), axis=0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM