比较数组中的值并计算范围 Numpy Python

Comparing values in an array and calculating the difference in ranges Numpy Python

我正在尝试编写一个函数来检查某个值是否在 val 103.0, 58.8, 35, -47 的值范围内下降超过 100,值从 103 变为 -47,即 - 150 也 58.8, 35, -47 值从 58 变为 -47,减少了 -105。所以这些是 2 个案例,从初始值下降到等于或超过 -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
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