是否有用于查找数组中大于阈值的第一个成员的函数

2024-04-27 01:13:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找到数组中第一个成员的索引,其中直到该点的累积和大于特定阈值,我得到的代码如下:

def calc(source, threshold):
    sum=0
    for counter, num in enumerate(source):
    sum = sum + num
    if sum >= threshold:
        return counter

它可以完成这项工作,但是当使用大型阵列时,执行需要很长时间,是否有一个函数可以完成这项工作?或者有没有其他更快的方法来达到同样的效果


Tags: 代码insourceforthresholdifdefcounter
2条回答

解决方案

您可以在一行中使用

  • a[a.cumsum() > threshold][0]用于匹配的value
  • np.where(a.cumsum() > threshold)[0][0]用于匹配的index

具体如下

a = np.array([10,20,30,40])
threshold = 30

# To get the first value that
# matches the condition
matched_value = a[a.cumsum() > threshold][0]
print(f'matched_value: {matched_value}')
# To get the first index that
# matches the condition
matched_index = np.where(a.cumsum() > threshold)[0][0]
print(f'matched_index: {matched_index}')

输出

matched_value: 30
matched_index: 2

范例

这是另一个例子

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

假设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]])

相关问题 更多 >