abe*_*ozz 16 python parsing pandas
使用python 2.7.5和pandas 0.12.0,我正在尝试使用'pd.io.parsers.read_fwf()'将固定宽度字体的文本文件导入到DataFrame中.我导入的值都是数字,但重要的是保留前导零,所以我想将dtype指定为字符串而不是int.
根据此函数的文档,read_fwf支持dtype属性,但是当我尝试使用它时:
data= pd.io.parsers.read_fwf(file, colspecs = ([79,81], [87,90]), header = None, dtype = {0: np.str, 1: np.str})
我收到错误:
ValueError: dtype is not supported with python-fwf parser
我已经尝试了尽可能多的变体,因为我可以设想'dtype = something',但它们都会返回相同的消息.
任何帮助将非常感激!
在@ TomAugspurger的示例基础上,不是指定dtypes,而是为要保留为str的列指定转换器:
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})
Run Code Online (Sandbox Code Playgroud)
导致
\n Unnamed: 1
0 121 0123
1 121 0012
2 121 0001
Run Code Online (Sandbox Code Playgroud)
转换器是从列名称或索引到函数的映射,用于转换单元格中的值(例如,int将它们转换为整数,浮点数转换为浮点数等)