简体   繁体   English

如何获取排序数组的索引,其中前n个值的摘要大于某个值

[英]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.

相关问题 如何只替换numpy数组中大于某个值的前n个元素? - How to replace only the first n elements in a numpy array that are larger than a certain value? 如何查找值大于numpy中某个阈值的数组的索引? - How to find the index of an array where the value is larger than some threshold in numpy? 如何替换大于特定阈值的数据帧的每一行中的前n个元素 - How to replace the first n elements in each row of a dataframe that are larger than a certain threshold 如何获取值大于 20 的总行的总和并删除小于某个值的行 - How to get the sum of total row where values greater than 20 and drop those less than a certain value 如何屏蔽索引小于某个值的数组 - How to mask an array where the index is less than a certain Numpy:获取索引大于值且条件为真的数组 - Numpy: get array where index greater than value and condition is true 在Python中,如何在排序列表中找到大于阈值的第一个值的索引? - In Python, how do you find the index of the first value greater than a threshold in a sorted list? 返回数组中高于特定概率的值的排序索引 - Return the sorted index of values above a certain probability in an array 如果一个元素小于或大于某个值,如何删除 2D numpy 数组中的列 - How to remove columns in 2D numpy array if one element is smaller or larger than a certain value 有效地查找数量最小的索引,该索引大于大型排序列表中的某个值 - Efficiently find index of smallest number larger than some value in a large sorted list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM