开发者社区> 问答> 正文

在Python中实现文件行的滑动窗口

我尝试使用Python在csv文件的行上实现滑动/移动窗口方法。每行可以有一个列,列的二进制值是或否。基本上,我想要减少“是”的声音。这意味着,如果我们在5个窗口(最多5个)中有3个yes行,那么就保留它们。但是如果有1或2,我们就把它们改成no。我该怎么做呢? 例如,下面的yes应该都变成no。

...
1,a1,b1,no,0.75
2,a2,b2,no,0.45
3,a3,b3,yes,0.98
4,a4,b4,yes,0.22
5,a5,b5,no,0.46
6,a6,b6,no,0.20
...

但在下面,我们保持原样(可能有5个窗口,其中3个是yes):

...
1,a1,b1,no,0.75
2,a2,b2,no,0.45
3,a3,b3,yes,0.98
4,a4,b4,yes,0.22
5,a5,b5,no,0.46
6,a6,b6,yes,0.20
...

我试图写一些东西,有一个5的窗口,但被卡住了(它是不完整的):

        window_size = 5 
        filename='C:\\Users\\username\\v3\\And-'+v3file.split("\\")[5]
        with open(filename) as fin:
            with open('C:\\Users\\username\\v4\\And2-'+v3file.split("\\")[5],'w') as finalout:
                line= fin.readline()
                index = 0
                sequence= []
                accs=[]
                while line:
                    print(line)
                    for i in range(window_size):
                        line = fin.readline()
                        sequence.append(line)
                    index = index + 1
                    fin.seek(index)

问题来源StackOverflow 地址:/questions/59380717/implement-sliding-window-on-file-lines-in-python

展开
收起
kun坤 2019-12-28 14:10:37 493 0
1 条回答
写回答
取消 提交回答
  • 可以使用collections.deque,将maxlen参数设置为所需的窗口大小,从而实现一个滑动窗口,跟踪最近5行的yes/no标志。在每一次迭代中,对yes进行计数,而不是在滑动窗口中计算yes的总数,以提高效率。当您有一个全尺寸的滑动窗口,并且yeses的数量大于2时,将这些yeses的行索引添加到一个应该保持原样的集合中。在重新设置输入的文件指针后的第二遍中,如果行索引不在集合中,则将yes改为noes:

    from collections import deque
    
    window_size = 5
    with open(filename) as fin, open(output_filename, 'w') as finalout:
        yeses = 0
        window = deque(maxlen=5)
        preserved = set()
        for index, line in enumerate(fin):
            window.append('yes' in line)
            if window[-1]:
                yeses += 1
            if len(window) == window_size:
                if yeses > 2:
                    preserved.update(i for i, f in enumerate(window, index - window_size + 1) if f)
                if window[0]:
                    yeses -= 1
        fin.seek(0)
        for index, line in enumerate(fin):
            if index not in preserved:
                line = line.replace('yes', 'no')
            finalout.write(line)
    

    演示:https://repl.it/@blhsing / StripedCleanCopyrightinfringement

    2019-12-28 14:10:44
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载