【问题标题】:read_fwf and decimal-less formattingread_fwf 和无十进制格式
【发布时间】:2014-04-10 13:29:35
【问题描述】:

固定格式的数据文件有时没有明确的小数点,而是依靠格式化字符串将整数解析为浮点数(例如,%4.2f)。 read_fwf 中是否内置了此类功能?即,有没有一种简单的方法可以将 1004 解析为 10.04?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用自定义转换器,在您阅读文件时即时转换:

    def convert_to_decimals(x):
        return x.format('4%.2f')
    
    df = pd.read_fwf('myfile', converters={'col_to_convert':convert_to_decimals})
    

    所以这里发生的情况是,我们正在定义一个转换函数,然后通过传递一个 dict 来设置 converters 参数,其中包含我们要转换的列作为键,函数名称作为转换函数。

    online docs

    【讨论】:

    • 这似乎不起作用。例如,'1004'.format('%4.2f') 或 '1004'.format('4%.2f') 返回 '1004'。因此,当我应用上述内容时,'col_to_convert' 具有对象的 dtype 而不是浮点数。另一方面, def convert_to_decimals(x): return float(x)/100 df = pd.read_fwf('myfile', converters={'col_to_convert':convert_to_decimals}) 会进行正确的转换。更有趣的是函数 convert_to_decimals(x,formatstring) 可以更灵活地进行转换。 (抱歉格式不好。)
    • 所以你希望 dtype 是浮点数,试试这个def convert_to_decimals(x): return float(x[:-2] + '.' + x[-2:])
    • @TedTo 对于自定义格式,您必须定义它并在读取文件或在读取后执行它时用作转换器参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多