【问题标题】:Comparing values in an array and calculating the difference in ranges Numpy Python比较数组中的值并计算范围内的差异 Numpy Python
【发布时间】:2021-07-25 01:43:00
【问题描述】:

我正在尝试编写一个函数来检查一个值是否在val103.0, 58.8, 35, -47 的值范围内下降超过 100,值从 103 变为 -47,即 -150 也是 58.8, 35, -47值从 58 变为 -47,减少了 -105。因此,有两种情况是从初始值下降到等于或超过 -100 的值。它检查数组中的每个值是否有 -100 的下降,直到数组末尾。因此,如果它采用数字7.4,那么它将检查数组的其余部分是否为1180.9, 0.6, 103.0, 58.8, 35, -47, 47.2, 78.1, 37.8,如果值为1180.9,那么它将检查值0.6, 103.0, 58.8, 35, -47, 47.2, 78.1, 37.8。我怎么能用 numpy 做到这一点。

import numpy as np 

val = np.array([7.4, 1180.9, 0.6, 103.0, 58.8, 35, -47, 47.2, 78.1, 37.8])
val2 = np.array([46.5, 55.7, 7.0, 19.6, 7.6, 36.5, 34.7, 101.9, 179.7, 85.5])
val3 = np.array([120, 20, -80, -5.5])

differences = 100

def run(values):
    minimums = np.subtract.accumulate(values)
    print(f'Number it has been below or equal to {differences} is {values}')
    return minimums
    
print(run(val))
print(run(val2))
print(run(val3))

预期输出:

Number it has been below or equal to -100 is 3
Number it has been below or equal to -100 is 0
Number it has been below or equal to -100 is 2

【问题讨论】:

    标签: arrays python-3.x numpy compare subtraction


    【解决方案1】:
    import numpy as np
    
    val = np.array([7.4, 1180.9, 0.6, 103.0, 58.8, 35, -47, 47.2, 78.1, 37.8]) 
    val2 = np.array([46.5, 55.7, 7.0, 19.6, 7.6, 36.5, 34.7, 101.9, 179.7, 85.5]) 
    val3 = np.array([120, 20, -80, -5.5]) 
    
    def run( arr, limit ): 
        row_mins = np.triu( arr[None, : ] - arr[ :, None ] ).min(axis = 1 ) 
        return np.count_nonzero( row_mins <= -limit ) 
    

    扩展:

    def run( arr, limit ):
        # Uncomment the print statements to see what is happening.
        temp = arr[None, : ] - arr[ :, None ]  # difference of each element all elements
        # print( temp )
        temp1 = np.triu( temp )  # Keep the upper triangle, set lower to zero
        # print( temp1 )
        row_mins = temp1.min( axis = 1 )   # Minimum for each row
        # print( row_mins )
        return np.count_nonzero( row_mins <= -limit ) # Count how many row_mins are <= limit
    

    结果:

    run(val, 100)   # 3
    run(val2, 100)  # 0
    run(val3, 100)  # 2
     
    

    【讨论】:

    • 谢谢它的工作我试图做相反的事情,而不是 100 的回撤寻找 100 的上行空间。但它并没有真正起作用我尝试了以下代码:row_mins = np.triu( arr[None, : ] + arr[ :, None ] ).min(axis = 1 ) return np.count_nonzero(row_mins &gt;= limit )
    • 我不确定您要做什么,但我认为您仍然想要差异,而不是总和,并且可能需要最大值,而不是最小值。所以row_maxs = np.triu( arr[None, : ] - arr[ :, None ] ).max(axis = 1 )。这行得通吗?
    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2022-08-07
    相关资源
    最近更新 更多