如何解决比较数组中的值并计算范围内的差异 Numpy Python
我正在尝试编写一个函数来检查值在 val
103.0,58.8,35,-47
的值范围之间是否下降了 100 以上,这些值从 103 变为 -47,也就是 -150 58.8,-47
值从 58 变为 -47,减少了 -105。因此,这两种情况是从初始值下降到等于或超过 -100 的值。它检查数组中的每个值是否下降了 -100,直到数组结束。因此,如果它采用数字 7.4
,那么它将检查数组的其余部分是否为 1180.9,0.6,103.0,-47,47.2,78.1,37.8
,如果值为 1180.9
,则它将检查值 0.6,37.8
。我怎么能用 numpy 做到这一点。
import numpy as np
val = np.array([7.4,1180.9,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,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。