Suppose I have a 1D array sorted in descending order, like:
arr = np.array([10, 10, 8, 5, 4, 4, 3, 2, 2, 2])
I want the index value, where the summation of this array starting from 0 to that index is greater than or equal to a specified target value. For example, let the target value be 40:
index=0 (0) => sum=10 (10)
index=1 (0,1) => sum=20 (10+10)
index=2 (0,1,2) => sum=28 (10+10+8)
index=3 (0,1,2,3) => sum=33 (10+10+8+5)
index=4 (0,1,2,3,4) => sum=37 (10+10+8+5+4)
index=5 (0,1,2,3,4,5) => sum=41 (10+10+8+5+4+4)
and finally I want to get the index value 5, since the sum 41 is greater than the target value 40. How can I do this in most Pythonic and appropriate way, so it can work with large numbers and large sized arrays.
Find the cumulative sum of the array with np.cumsum()
. Find the index of the first element of the cumsum that is greater than the target value with np.where()
:
cumsum = arr.cumsum()
np.where(cumsum > 40)[0][0]
# 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.