[英]How to get the index of an sorted array where the summary of first n values larger than a certain value
if I got a sorted numpy array A=[1, 2, 3, 4, 5, 6], I want to get the index where the sum of A[0: index] that bigger than a certain number (supposed to be 9, in this case, the value of index should be 3), how can I write it in python? 如果我得到一个排序的numpy数组A = [1,2,3,4,5,6],我想获得索引,其中A [0:index]的总和大于某个数字(应该是9) ,在这种情况下,索引的值应该是3),我怎么能用python写呢?
I think maybe I can use np.where() or np.cumsum() but it doesn't work 我想也许我可以使用np.where()或np.cumsum()但它不起作用
np.argwhere(np.cumsum(A) > 9)
of course, it is wrong, so what is the correct method? 当然,这是错误的,那么正确的方法是什么?
You were close. 你很亲密 You can just use
argmax
as follows. 您可以按如下方式使用
argmax
。 Also, when using argmax, add a check to ensure that atleast 1 value crosses the threshold. 此外,使用argmax时,添加一个检查以确保至少1值超过阈值。
threshold = 9
temp = np.cumsum(A) > threshold
if temp.any():
print(np.argmax(temp))
else:
print("Threshold never crossed")
I suggest: 我建议:
def foo(array, threshold):
valid_entries = np.cumsum(array) > threshold
return np.argmax(valid_entries) if np.any(valid_entries) else None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.