繁体   English   中英

Python numpy数组对某些索引求和

[英]Python numpy array sum over certain indices

如何仅对 numpy 数组上的索引列表执行求和,例如,如果我有一个数组a = [1,2,3,4]和要求和的索引列表,则indices = [0, 2]和 I要快速操作,给我答案4 ,因为在索引0和索引2值相加的值a4

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

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

接受的a[indices].sum()方法复制数据并创建一个新数组,如果数组很大,这可能会导致问题。 np.sum实际上有一个参数来屏蔽列,你可以这样做

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

它不复制任何数据。

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

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

尝试:

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

暂无
暂无

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

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