You need to enable JavaScript to run this app. pd.read_fwf使用colspecs时列匹配异常、读取值错误问题排查
优惠活动
大模型
产品
解决方案
定价
更多

pd.read_fwf使用colspecs时列匹配异常、读取值错误问题排查

问题原因

  • colspecs偏移量计算错误:你提供的测试文件每行有效内容前有18个前导空格,Python索引从0开始计数,因此有效内容的第一个字符(即第一个1)对应的原始行索引是18,你设置的colspecs起始偏移为19,导致字段全部错位,第二个1被跳过,后续S、C等字符依次顺位被读取到错误的字段中。
  • 未指定数据类型为字符串:pandas默认会将纯数字内容识别为数值型,会自动截断前导0,因此你预期的059会被转换为59。

修复代码

方案1:按原始行位置修正偏移

import pandas as pd

specs_test =[(18, 19),(19, 20),(20, 22),(22, 25)]
names_test = ["Record_Type","Resident_Status","State_Occurrence_FIPS","County_Occurrence_FIPS"]

# 指定dtype=str保留所有字符的原始格式,避免丢失前导0
test_l = pd.read_fwf('test.txt', header=None, names=names_test, colspecs=specs_test, dtype=str)

方案2:跳过前导空格后从0计数偏移(更不易出错)

import pandas as pd

# 跳过前导空格后,有效内容从索引0开始计算
specs_test =[(0, 1),(1, 2),(2, 4),(4, 7)]
names_test = ["Record_Type","Resident_Status","State_Occurrence_FIPS","County_Occurrence_FIPS"]

test_l = pd.read_fwf('test.txt', header=None, names=names_test, colspecs=specs_test, dtype=str, skipinitialspace=True)

执行以上任意一种方案后,第一行的输出就会符合你的预期:1 1 SC 059。

内容的提问来源于stack exchange,提问作者BobbyF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 02:06:03