简体   繁体   English

如何找到总和大于目标值的数组的索引?

[英]How to find the index of an array where summation is greater than a target value?

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.我想要索引值,其中从 0 到该索引的此数组的总和大于或等于指定的目标值。 For example, let the target value be 40:例如,让目标值为 40:

index=0 (0) => sum=10 (10)索引=0 (0) => 总和=10 (10)

index=1 (0,1) => sum=20 (10+10)索引=1 (0,1) => 总和=20 (10+10)

index=2 (0,1,2) => sum=28 (10+10+8)索引=2 (0,1,2) => 总和=28 (10+10+8)

index=3 (0,1,2,3) => sum=33 (10+10+8+5)索引=3 (0,1,2,3) => 总和=33 (10+10+8+5)

index=4 (0,1,2,3,4) => sum=37 (10+10+8+5+4)索引=4 (0,1,2,3,4) => 总和=37 (10+10+8+5+4)

index=5 (0,1,2,3,4,5) => sum=41 (10+10+8+5+4+4)索引=5 (0,1,2,3,4,5) => 总和=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.最后我想获得索引值 5,因为总和 41 大于目标值 40。我如何以大多数 Pythonic 和适当的方式执行此操作,以便它可以处理大数字和大尺寸 arrays。

Find the cumulative sum of the array with np.cumsum() .使用np.cumsum()查找数组的累积和。 Find the index of the first element of the cumsum that is greater than the target value with np.where() :使用np.where()大于目标值的 cumsum 的第一个元素的索引:

cumsum = arr.cumsum()
np.where(cumsum > 40)[0][0]
# 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM