使用 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/