Есть ли функция для поиска первого члена в массиве, который больше порога - PullRequest
0 голосов
/ 05 мая 2020

Мне нужно найти индекс первого члена в массиве, где совокупная сумма до этой точки больше заданного порога c, код, который я получил, следующий:

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

It выполняет свою работу, но при работе с большими массивами требуется много времени для выполнения, есть ли функция, которая это делает? или есть другой более быстрый способ достичь того же результата?

Ответы [ 2 ]

0 голосов
/ 05 мая 2020

Решение

Вы можете сделать это в одной строке, используя

  • 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
0 голосов
/ 05 мая 2020

предположим, что 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]])
...