根据列表跟踪值低于或高于阈值的次数
Tracking how many times value went below or above threshold based on list
我有一个包含值的列表,我正在寻找方法来跟踪这些值是否低于某个值,然后是否又回到该值之上(可能是次数)
假设我的 lisy 看起来像:
list1 = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16]
我需要一些东西来告诉我,值在最初低于 15 后又回升到 15 以上两次或 x 次。
有人知道如何解决这个问题吗?
pos_count = 0
neg_count = 0
for x in range(len(list1)-1):
if list1[x] <= 15 and list1[x + 1] > 15:
neg_count += 1
elif list1[x] >= 15 and list1[x + 1] < 15:
pos_count += 1
print(pos_count)
print(neg_count)
您可以简单地检查 negative/positive 与 15 的区别。
像这样:
l = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16] #Your list
import numpy as np
arr = np.asarray(l) #Convert to numpy-array
#Now apply the function to check the difference from 15
result = np.apply_along_axis(lambda x: x - 15, axis=0, arr=arr)
这导致:
数组([ 5, 3, 1, 0, -2, -3, 1, 2, -1, -4, 1])
如果你想检查所有正值,你可以这样做:
pos = result[result >= 0] #All positive values
neg = result[result < 0] #All negative values
如果你想统计这种情况发生的频率,你可以统计长度:
len(pos) #Number of positives
len(neg) #Number of negatives
我有一个包含值的列表,我正在寻找方法来跟踪这些值是否低于某个值,然后是否又回到该值之上(可能是次数)
假设我的 lisy 看起来像:
list1 = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16]
我需要一些东西来告诉我,值在最初低于 15 后又回升到 15 以上两次或 x 次。 有人知道如何解决这个问题吗?
pos_count = 0
neg_count = 0
for x in range(len(list1)-1):
if list1[x] <= 15 and list1[x + 1] > 15:
neg_count += 1
elif list1[x] >= 15 and list1[x + 1] < 15:
pos_count += 1
print(pos_count)
print(neg_count)
您可以简单地检查 negative/positive 与 15 的区别。 像这样:
l = [20, 18, 16, 15, 13, 12, 16, 17, 14, 11, 16] #Your list
import numpy as np
arr = np.asarray(l) #Convert to numpy-array
#Now apply the function to check the difference from 15
result = np.apply_along_axis(lambda x: x - 15, axis=0, arr=arr)
这导致: 数组([ 5, 3, 1, 0, -2, -3, 1, 2, -1, -4, 1])
如果你想检查所有正值,你可以这样做:
pos = result[result >= 0] #All positive values
neg = result[result < 0] #All negative values
如果你想统计这种情况发生的频率,你可以统计长度:
len(pos) #Number of positives
len(neg) #Number of negatives