我需要找到一个数组中第一个成员的索引,在该数组中直到该点的累积总和大于特定阈值,我得到的代码是这样的:
def calc(source, threshold):
sum=0
for counter, num in enumerate(source):
sum = sum + num
if sum >= threshold:
return counter
它可以完成工作,但是在处理大型数组时需要花费很长时间才能执行,是否有执行此功能的函数?还是有其他更快的选择来达到相同的结果?
假设a是一个numpy数组[10,20,30,40],阈值为30。返回索引的代码,该索引的累积和大于或等于阈值
import numpy as np
a= np.array([10,20,30,40])
threshold = 30
a = list(a)
indices_list = [a.index(item) for i,item in enumerate(a) if sum(a[:i+1])>=threshold]
if indices_list !=[]:
print('Required element is',a[indices_list[0]])
您可以按如下所示在单行a[a.cumsum() > threshold][0]
中进行此操作。
a = np.array([10,20,30,40])
threshold = 30
a[a.cumsum() > threshold][0]
输出:
30
这里是另一个例子。
import numpy as np
#a = np.random.randint(0, high=100, size=10)
a = [75, 38, 23, 59, 0, 16, 96, 60, 52, 58]
a = np.array(a)
print(f'array: {a}')
# Cumulative sum
print(f'cumsum: {a.cumsum()}')
# First element in the array where the
# cumulative sum is greater than a given value
threshold = 180
value = a[a.cumsum() > threshold][0]
print(f'Target Cumsum Threshold: {threshold} \n' + f'Value: {value}')
输出:
array: [75 38 23 59 0 16 96 60 52 58]
cumsum: [ 75 113 136 195 195 211 307 367 419 477]
Target Cumsum Threshold: 180
Value: 59