首页 > 解决方案 > 对某些标准使用简单的计数方法

问题描述

我有一个像

x y
1 0.34
2 0.3432
3 0.32
4 0.35
5 0.323
6 0.3623
7 0.345
8 0.32
9 0.31
10 0.378
11 0.34
12 0.33
13 0.31
14 0.33
15 0.34

对于这个数据集,我想执行一项任务,该任务将遍历我的数据集,如果出现的长度高于 M,将计算高于截止值的出现次数。

截止和 M 将是系统参数。

因此,如果截止值为 0.32 且 M 为 1,它将打印出一个列表,如

[2, 4, 3, 2]

逻辑:第二列中的前两个值大于 0.32,并且长度大于 M=1,因此打印出 2 和 4,3,2 依此类推。

我需要帮助来编写参数,以便如果 x >cutoff 并且损坏的长度 >M 它将打印出损坏帧的长度(因此与上面的输出相同)。有什么帮助吗?

结构应如下所示(我不确定如何将参数放置在 XXX 的位置)

def get_input(filename):
    with open(filename) as f:
        next(f) # skip the first line
        input_list = []
        for line in f:
            input_list.append(float(line.split()[1]))

    return input_list


def countwanted(input_list, wantbroken, cutoff,M):

    def whichwanted(x):
        if(wantbroken): return x > cutoff
        else: return x < cutoff

XXX I think here I need to add the criteria for M but not sure how?

filename=sys.argv[1]
wantbroken=(sys.argv[2]=='b' or sys.argv[2]=='B')
cutoff=float(sys.argv[3])
M=int(sys.argv[4])

input_list = get_input(filename)

broken,lifebroken=countwanted(input_list,True,cutoff,M)
#closed,lifeclosed=countwanted(input_list,False,cutoff,M)
print(lifebroken)
#print(lifeclosed)

或者也许有一种更简单的方法来编写它。

标签: pythonnumpy

解决方案


你可以使用 numpy,这让生活变得更轻松。

首先,让我们看一下文件加载器。np.loadtxt可以在一行中做同样的事情。

y = np.loadtxt(filename, skiprows=1, usecols=1)

现在创建一个掩码,其中构成您的阈值以上运行的值:

b = (y > cutoff)  # I think you can figure out how to switch the sense of the test

其余的很容易,并且基于这个问题

b = np.r_[0, b, 0]       # pad the ends
d = np.diff(b)           # find changes in state
start, = np.where(d > 0) # convert switch up to start indices
end, = np.where(d < 0)   # convert switch down to end indices
len = end - start        # get the lengths

现在您可以M申请len

result = len[len >= M]

如果您想使用列表,itertools.groupby也提供了一个很好的解决方案:

grouper = it.groupby(y, key=lambda x: x > cutoff)
result = [x for x in (len(list(group)) for key, group in grouper if key) if x >= M]

推荐阅读