-3

日志格式是这样的 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。我怎样才能再次改变它?

4

1 回答 1

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]]
于 2013-10-10T07:12:59.967 回答