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 并且损坏的长度 >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)
或者也许有一种更简单的方法来编写它。
解决方案
你可以使用 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]
推荐阅读
- pandas - 在 CSV 文件上使用 pandas,如果“日期”列的格式为“MM/DD/YYYY”,如何按“月”过滤数据集
- microsoft-graph-api - 无法将“In-Reply-To”参数传递给 Microsoft Graph sendMail
- sql - 存储过程性能问题 临时表中有 150 万条记录
- laravel - 127.0.0.1:8000 在 laravel 项目中不断加载
- asp.net - 发送电子邮件在本地工作而不是在服务器上
- node.js - “查询值必须是一个数组”...?
- java - 在 Java 中,通过 new 运算符是否可以创建具有相同字符串内容的不同对象?
- javascript - document.querySelectorAll("[value='a']") 的返回值在元素值被修改后不会改变
- javascript - 使用 RXJS 的 Redux Observable Epic 条件语句
- javascript - 如何使点击事件适用于同名的多个类