如何仅对 numpy 数组上的索引列表执行求和,例如,如果我有一个数组a = [1,2,3,4]
和要求和的索引列表,则indices = [0, 2]
和 I要快速操作,给我答案4
,因为在索引0和索引2值相加的值a
是4
You can use sum
directly after indexing with indices
:
a = np.array([1,2,3,4])
indices = [0, 2]
a[indices].sum()
The accepted a[indices].sum()
approach copies data and creates a new array, which might cause problem if the array is large. np.sum
actually has an argument to mask out colums, you can just do
np.sum(a, where=[True, False, True, False])
Which doesn't copy any data.
The mask array can be obtained by:
mask = np.full(4, False)
mask[np.array([0,2])] = True
Try:
>>> a = [1,2,3,4]
>>> indices = [0, 2]
>>> sum(a[i] for i in indices)
4
If you have a lot of numbers and you want high speed, then you need to use numpy:
>>> import numpy as np
>>> a = np.array([1,2,3,4])
>>> a[indices]
array([1, 3])
>>> np.sum(a[indices])
4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.