2013-02-27 34 views
0

我想创建一个小类来处理从ASCII文件读取数据。以下是我写的代码。如何在构建DataFrame时模拟转换器?

class EyelinkParser(object): 
    eyesample = namedtuple('Eyesample', ('time', 'x', 'y', 'pupil')) 
    etevent = namedtuple('EyeTrackerEvent', ('time', 'msg')) 
    _pos_cnvrt = lambda v: float(v.strip()) if '.' not in v else str('NaN') 
    converters = {'time': lambda t: int(t.strip()), 
        'x': _pos_cnvrt, 
        'y': _pos_cnvrt, 
        'pupil': _pos_cnvrt, 
        'msg': lambda s: s.strip() 
       } 

    def __init__(self, fileobj): 
     self.fileobj = fileobj 
     self.started = False 

     self.sample = [] 
     self.event = [] 

     self.parse() 

    def parse(self): 
     for line in self.fileobj: 
      line = line.split('\t') 
      if line[0] in ['START', 'END']: 
       self.started = line[0] == 'START' 

      if self.started: 
       self.process_line(line) 

     self.sample = pd.DataFrame(self.sample, columns=['time', 'x', 'y', 'pupil'], converters=self.converters) 
     self.event = pd.DataFrame(self.event, columns=['time', 'msg'], converters=self.converters) 

    def process_line(self, line): 
     if len(line) == 2 and line[0] == 'MSG': 
      msg_data = line[1].split() 
      if len(msg_data) == 2: 
       self.event.append(self.etevent(*msg_data)) 
     elif len(line) == 4: 
      # TODO: replace '.' with NaNs 
      self.sample.append(self.eyesample(*line)) 

显然DataFrame类不支持转换器。有没有简单的方法来完成我想要做的事情?

总之,我怎么可以指定在DataFrame的每一列的值的类型转换?

回答

1

我不知道该怎么做明确以此为调用数据帧的一部分。

传递一个类型,每一列:

self.sample['x'].astype(int) 

但因为你传递的功能,你可能需要当我碰到的这个问题,我用下面的事实之后铸造使用以下:

self.sample['x'].map(_pos_cnvrt) 
self.sample['msg'].map(lambda s:s.strip()) 

此外,熊猫拥有一些量化的字符串方法烤制的帮助:

self.sample['msg'].str.strip() 
+0

哇,太棒了!我不知道有用字符串方法烘焙过的东西,虽然我以前见过'astype',但我完全忘了它。非常感谢! – blz 2013-02-28 20:38:10