【问题标题】:Is there a function for finding the first member in an array which greater then a threshold是否有用于查找数组中大于阈值的第一个成员的函数
【发布时间】:2020-05-05 04:50:21
【问题描述】:

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

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

它可以完成这项工作,但是在处理大型数组时需要很长时间才能执行,有没有一个函数可以做到这一点?或者有没有其他更快的选择来达到同样的效果?

【问题讨论】:

  • 你在使用 numpy 吗? source 是一个 numpy 数组还是什么?
  • 是的,它的 numpy,抱歉没有提到它

标签: python performance numpy cumsum


【解决方案1】:

解决方案

您可以在一行中使用

  • 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

【讨论】:

  • 这会返回值,而不是索引,这是问题所要求的
  • @talonmies 感谢您指出这一点。我会更新解决方案。
  • @Dan 请考虑投票答案,如果你接受它。谢谢。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2017-02-13
    • 2014-07-14
    相关资源
    最近更新 更多