如何在python中获取gap列?

时间:2013-10-10 03:57:48

标签: python numpy

日志格式就是这样 100 0 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 11 1 12 1 13 1 14 1 15 1 16 1 17 1 18 1 19 1 20 1 21 1 22 1 23 1 24 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1

我编写python代码,

def read_data(filename, sep=" ", filt=int):

    def split_line(line):
        return line.split(sep)

    def apply_filt(values):
        return map(filt, values)

    def process_line(line):
        return apply_filt(split_line(line))

    f = open(filename)
    lines = map(process_line, f.readlines())
    # "[1]" below corresponds to x0
    X = np.array([ l[3:] for l in lines])
    # "or -1" converts 0 values to -1
    Y = np.array([l[1] or -1 for l in lines])
    f.close()

    return X, Y

X是从3个字体中获取的,现在我想从第三个列中获取每个间隙列,如何更改代码,并且X将为1 1 1 1 1 1 1 1 1 1 Y是l [1]或-1。但是如果l1大于0我想得到1,如果l1等于0则得-1.

1 个答案:

答案 0 :(得分:0)

我猜你想要这样的东西:

import numpy as np
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

def read_data(f, sep=" ", filt=int):

    def split_line(line):
        return line.split(sep)

    def apply_filt(values):
        return map(filt, values)

    def process_line(line):
        return apply_filt(split_line(line))

    #f = open(filename)
    lines = np.array(map(process_line, f.readlines()), dtype=int)
    # "[1]" below corresponds to x0
    X = lines[:,3::2]
    # "or -1" converts 0 values to -1
    Y = lines[:,:]    
    Y[Y<=0]=-1

    f.close()

    return X, Y


reader = StringIO('100 0 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 11 1 12 1 13 1 14 1 15 1 16 1 17 1 18 1 19 1 20 1 21 1 22 1 23 1 24 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1\n')    


x,y = read_data(reader)
reader.close

print 'X:', x
print 'Y:', y

给出:

X: [[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]]
Y: [[100  -1  -1   1   1   1   2   1   3   1   4   1   5   1   6   1   7   1
    8   1   9   1  10   1  11   1  12   1  13   1  14   1  15   1  16   1
   17   1  18   1  19   1  20   1  21   1  22   1  23   1  24   1  25   1
   26   1  27   1  28   1  29   1  30   1  31   1  32   1  33   1  34   1
   35   1]]