我正在尝试创建一个小类来处理从 ASCII 文件中读取数据。下面是我写的代码。
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
该类不支持转换器。有没有一种简单的方法来完成我想要做的事情?
总而言之,如何在 a 的每一列中指定值的类型转换DataFrame
?