python read_fwf 错误 : 'dtype is not supported with python-fwf parser'

标签 python parsing pandas

使用 python 2.7.5 和 pandas 0.12.0,我正在尝试使用“pd.io.parsers.read_fwf()”将固定宽度字体的文本文件导入 DataFrame。我导入的值都是数字,但保留前导零很重要,因此我想将 dtype 指定为字符串而不是 int。

根据documentation for this function , read_fwf 支持 dtype 属性,但是当我尝试使用它时:

data= pd.io.parsers.read_fwf(文件, colspecs = ([79,81], [87,90]), header = None, dtype = {0: np.str, 1: np .str})

我得到错误:

ValueError:python-fwf 解析器不支持 dtype

我已经尝试了尽可能多的变体来设置“dtype = something”,但所有变体都返回相同的消息。

任何帮助将不胜感激!

最佳答案

不是指定数据类型,而是为要保留为 str 的列指定一个转换器,以@TomAugspurger 的示例为基础:

from io import StringIO
import pandas as pd
data = StringIO(u"""
121301234
121300123
121300012
""")

pd.read_fwf(data, colspecs=[(0,3),(4,8)], converters = {1: str})

导致

    \n Unnamed: 1
0  121       0123
1  121       0012
2  121       0001

转换器是从列名或索引到函数的映射,用于转换单元格中的值(例如,int 会将它们转换为整数,将 float 转换为 float 等)

关于 python read_fwf 错误 : 'dtype is not supported with python-fwf parser' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472566/

相关文章:

python - 如何根据文件创建 QActions 及其信号

objective-c - 如何确定C或Objective-C中的URL、URI和Path?

两个不同目录中的 Python(一个指定目录和一个隐藏目录)

python - 为什么 pandas 逻辑运算符不像它应该的那样在索引上对齐?

python - 使用 Python 创建 SVG

python - 您如何以编程方式设置属性?

python - 在 Python 中通过套接字发送的字符串一旦 .recv'd 后将不会与等效字符串进行比较

c - 使用 fscanf 确定您正在读取 int 还是 double

xml - 将非结构化文档解析为 XML

python - 如何将具有相同文件名的 csv 导入数据框,应用一些程序,然后合并?