gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:06:11 24 4
gpt4 key购买 nike

在使用 Python (3.4.3) 的 pandas (0.18.1) 中使用 read_fwf 函数读取固定宽度文件时,可以使用 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

是否有专门针对此的文档?简单的解决方法是包含第一列,然后将其删除,但我想验证这是一个错误还是我误解了预期的行为。

最佳答案

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

关于python - 如果 colspecs 参数不包含第一列,则 Python 中 pandas 中的 read_fwf 不使用注释字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com