Решение
Вы можете сделать это в одной строке, используя
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