使用pandas(0.18.1)中的read_fwf
函数和Python(3.4.3)读取固定宽度文件时,可以使用comment
参数指定注释字符。我希望所有以注释字符开头的行都会被忽略。但是,如果您未在colspecs
中的任何列中指定文件中的第一列,则似乎不会使用注释字符。
import io, sys
import pandas as pd
sys.version
# '3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)]'
pd.__version__
# '0.18.1'
# Two input files, first line is comment, second line is data.
# Second file has a column (with the letter A)
# that I don't want at start of data.
string = "#\n1K\n"
off_string = "#\nA1K\n"
# When using skiprows to skip commented row, both work.
pd.read_fwf(io.StringIO(string), colspecs = [(0,1), (1,2)], skiprows = 1, header = None)
# 0 1
# 0 1 K
pd.read_fwf(io.StringIO(off_string), colspecs = [(1,2), (2,3)], skiprows = 1, header = None)
# 0 1
# 0 1 K
# If a comment character is specified, it only works when the colspecs
# includes the column with the comment character.
pd.read_fwf(io.StringIO(string), colspecs = [(0,1), (1,2)], comment = '#', header = None)
# 0 1
# 0 1 K
pd.read_fwf(io.StringIO(off_string), colspecs = [(1,2), (2,3)], comment = '#', header = None)
# 0 1
# 0 NaN NaN
# 1 1.0 K
有没有专门提到这个的文件?简单的解决方法是包含第一列,然后删除它,但我想验证这是一个错误还是我对预期行为的误解。
答案 0 :(得分:5)
我认为这是一个错误,文档中的规范说“如果该行以注释开头,则会跳过整行”。问题是,在FixedWidthReader.__next__
或PythonParser
检查评论之前,列由CParserWrapper
进行了子集化。相关代码位于io/parsers.py
。