如果colspecs参数不包含第一列,Python中pandas中的read_fwf不使用注释字符

时间:2016-08-30 19:12:09

标签: python python-3.x pandas

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

有没有专门提到这个的文件?简单的解决方法是包含第一列,然后删除它,但我想验证这是一个错误还是我对预期行为的误解。

1 个答案:

答案 0 :(得分:5)

我认为这是一个错误,文档中的规范说“如果该行以注释开头,则会跳过整行”。问题是,在FixedWidthReader.__next__PythonParser检查评论之前,列由CParserWrapper进行了子集化。相关代码位于io/parsers.py