You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python CSV转字典替换空值报ValueError 无pandas实现方案咨询

问题根因说明

你遇到的报错是原注释代码使用list.insert()方法导致的:insert(10,0)是在列表第10位插入新元素,原第10位及之后的所有元素都会后移一位,后续你取line[17]的时候已经不是原来的年薪字段,错位后拿到了其他列的字符串(报错里的FALSE就是错位后拿到的性别字段值),才会出现int转换失败的问题。


问题1:非pandas实现指定列空字符串替换方案

有三个常用可行方案:

  • 方案1:直接修改对应下标值,不要用insert。判断到第10列为空时直接执行line[10] = 0即可,不会改变列表长度,也不会出现字段错位问题
  • 方案2:构造字典时动态判断,不需要提前修改line内容。在给Dependants字段赋值时写为int(line[10]) if line[10].strip() else 0,既完成了空值替换也直接做了类型转换
  • 方案3:封装通用替换函数,如果后续还有其他列需要做类似空值替换,可以写个辅助函数统一处理,避免重复代码:
def replace_empty(val, default=0):
    return int(val) if val.strip() else default

调用的时候直接写'Dependants': replace_empty(line[10])即可。


问题2:获取空值修正的行号实现

只需要初始化一个空列表存储修正行号,每次触发空值替换逻辑的时候,把当前行号存入列表即可。注意enumerate默认从0开始计数,line_number=0对应表头行,数据行的line_number如果要匹配CSV文件打开后的实际行号(和Excel显示行号一致),需要+1,可根据自己的需求选择存储逻辑。


修正后完整可运行代码
import csv

filename = "替换为你的CSV文件路径.csv"
my_dic = []
fixed_line_numbers = [] # 存储所有发生空值修正的行号

with open(filename,'r') as input_file:
    csv_reader = csv.reader(input_file,delimiter = ',')
    for line_number, line in enumerate(csv_reader):
        if line_number == 0: # 跳过表头
            continue
        # 空值替换逻辑
        if line[10].strip() == '':
            line[10] = 0
            # 此处存储的是CSV文件的实际行号,和Excel打开显示的行号一致
            fixed_line_numbers.append(line_number + 1)
        my_dic.append({
            'First Name':line[11],
            'Last name':line[13],
            'Age(Years)':int(line[3]),
            'Sex':line[18],
            'type of car':line[16],
            'Marital Status':line[14],
            'Dependants':line[10],
            'Yearly Salary':int(line[17]),
            'Yearly Pension':int(line[15]),
            'Company':line[5],
            'Commuted Distance':float(line[4]),
            'vehicle':{
                'Make':line[19],
                'model':line[20],
                'year':int(line[21]),
                'category':line[22]
            },
            'Credit Card':{
                'Start Date':line[6],
                'End Date':line[7],
                'Card number':line[8],
                'Card CCV':int(line[9]),
                'iban':line[12]
            },
            'Address':{
                'Street':line[0],
                'City':line[1],
                'Postcode':line[2]
            }
        })

# 可直接打印查看所有修正过的行号
print("发生空值修正的行号:", fixed_line_numbers)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:39:00