对某些标准使用简单计数法

2024-06-28 20:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据集

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 and length of breaked为>;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)

或者有一个更简单的方法来写。你知道吗


Tags: 数据gtinput参数returndefsysline
1条回答
网友
1楼 · 发布于 2024-06-28 20:14:32

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

首先,让我们看看文件加载器。^{}可以在一行中做同样的事情。你知道吗

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

剩下的很简单,基于this question

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]

如果您想使用列表,^{}还提供了一个很好的解决方案:

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]

相关问题 更多 >