Python numpy数组求和某些索引

时间:2017-12-09 23:39:28

标签: python numpy sum indices

如何仅针对numpy数组的索引列表执行求和,例如,如果我有一个数组a = [1,2,3,4]和一个索引列表总和,indices = [0, 2]并且我希望快速操作给我答案4,因为a中索引0和索引2的求和值为4

3 个答案:

答案 0 :(得分:8)

您可以在使用sum索引后直接使用indices

a = np.array([1,2,3,4])
indices = [0, 2] 
a[indices].sum()

答案 1 :(得分:1)

尝试:

>>> a = [1,2,3,4]
>>> indices = [0, 2]
>>> sum(a[i] for i in indices)
4

更快

如果您有很多数字而且想要高速,那么您需要使用numpy:

>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> a[indices]
array([1, 3])
>>> np.sum(a[indices])
4

答案 2 :(得分:0)

已接受的a[indices].sum()方法复制数据并创建一个新数组。 np.sum实际上有一个掩盖列的参数,您可以这样做

np.sum(a, where=[True, False, True, False])

不复制任何数据。

可以通过以下方式获取掩码数组:

mask = np.full(4, False)
mask[np.array([0,2])] = True