Python:删除连续的区域

时间:2013-03-19 16:36:58

标签: python sequencing

我有一个.txt,例如(标签分隔):

1 2345
1 2346
1 2347
1 2348
1 2412
1 2413
1 2414

前四个连续行包含连续的整数值2345到2348.类似地,最后三行包含连续值2412到2414.我想对它们进行分组,使得这些连续值集的最小值和最大值出现在单行如下所示:

1 2345 2348
1 2412 2414

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用稍微修改过的Raymond Hettinger's cluster function版本:

def cluster(data, maxgap):
    """Arrange data into groups where successive elements
       differ by no more than *maxgap*

        >>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
        [[1, 6, 9], [100, 102, 105, 109], [134, 139]]

        >>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
        [[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]

    https://stackoverflow.com/a/14783998/190597 (Raymond Hettinger)
    """
    groups = [[data[0]]]
    for x in data[1:]:
        if abs(x - groups[-1][-1]) <= maxgap:
            groups[-1].append(x)
        else:
            groups.append([x])
    return groups

data = []
with open('data.txt', 'r') as f:
    for line in f:
        _, num = line.split()
        data.append(int(num))
for row in cluster(data, 1):
    print('1 {s} {e}'.format(s=row[0], e=row[-1]))

产量

1 2345 2348
1 2412 2414

答案 1 :(得分:2)

使用csv模块读取和写入数据,并跟踪“下一个”组的开始时间:

import csv

def grouped(reader):
    start = end = next(reader)
    print start, end
    for row in reader:
        if int(row[1]) - 1 != int(end[1]):
            yield (start, end)
            start = end = row
        else:
            end = row
    yield (start, end)

with open('inputfile.csv', 'rb') as inf, open('outputfile.csv', 'wb') as outf:
    inputcsv = csv.reader(inf, delimiter='\t')
    outputcsv = csv.writer(outf, delimiter='\t')
    for start, stop in grouped(inputcsv):
        outputcsv.writerow(start + stop[1:])

这写道:

1   2345    2348
1   2412    2414

outputfile.csv输入。

此解决方案永远不会在内存中保留超过3行的数据,因此您应该能够在其中放置任意大小的CSV文件。

答案 2 :(得分:0)

numpy提供了一些可以提供帮助的工具:

In [90]: import numpy as np

In [91]: x = np.loadtxt('seq.dat', dtype=int)

In [92]: x
Out[92]: 
array([[   1, 2345],
       [   1, 2346],
       [   1, 2347],
       [   1, 2348],
       [   1, 2412],
       [   1, 2413],
       [   1, 2414],
       [   1, 2500],
       [   1, 2501],
       [   1, 2502],
       [   2, 3000],
       [   2, 3001],
       [   2, 3100],
       [   2, 3101],
       [   2, 3102],
       [   2, 3103]])

In [93]: skip = np.where(np.diff(x[:,1]) != 1)[0]

In [94]: istart = np.hstack((0, skip + 1))

In [95]: istop = np.hstack((skip, -1))

In [96]: groups = np.hstack((x[istart], x[istop, 1:]))

In [97]: groups
Out[97]: 
array([[   1, 2345, 2348],
       [   1, 2412, 2414],
       [   1, 2500, 2502],
       [   2, 3000, 3001],
       [   2, 3100, 3103]])

分组时会忽略第一列数据,因此如果第一列可能影响组的形成方式,则需要进行一些调整。