【问题标题】:How can I emulate converters when constructiing a DataFrame?构建 DataFrame 时如何模拟转换器?
【发布时间】:2013-02-13 14:47:56
【问题描述】:

我正在尝试创建一个小类来处理从 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 类不支持转换器。有没有简单的方法来完成我想做的事情?

总之,如何指定DataFrame 的每一列中值的类型转换?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我不知道如何在调用 DataFrame 时显式执行此操作。当我遇到这个问题时,我使用以下两种方法之一:

    向每一列传递一个类型:

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

    但是由于您要传递函数,因此您可能需要使用以下内容:

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

    此外,pandas 还提供了一些向量化字符串方法来提供帮助:

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

    【讨论】:

    • 哇,太棒了!我不知道有字符串方法,虽然我过去见过astype,但我完全忘记了它。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2010-11-06
    • 2012-05-21
    • 2020-07-14
    • 2022-06-14
    • 2017-09-16
    相关资源
    最近更新 更多