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

CSV转float触发ValueError问题求助(附Python代码与数据)

问题排查与解决:CSV数值列转float触发ValueError

核心问题分析

从报错信息和数据样本看,有三个直接诱因:

  • 未跳过表头行:代码直接遍历所有行,把第一行的表头字符串(如Access to clean fuels and technologies for cooking (% of population) [EG.CFT.ACCS.ZS])传入float()转换,必然触发ValueError。
  • 空值标记未处理:CSV中用..表示空值,直接对这类字符串做数值转换也会报错。
  • 末尾无效行干扰:CSV末尾存在空行和注释行(如Data from database: World Development Indicators),这些行的列值为空,转换时同样会出错。

解决方案

1. 跳过表头行

在遍历数据前,先调用next(csvreader)读取并跳过表头。

2. 处理空值..

转换数值前先判断字段是否为..,可将其转为None或指定默认值(如0.0)。

3. 过滤无效行

判断行是否包含有效数据(比如检查Country Code列是否非空),跳过空行和注释行。

修改后的代码

def create_info(self, country_data):
    with open(country_data, "r") as csvfile:
      csvreader = csv.reader(csvfile)
      # 跳过表头行
      next(csvreader)
      for words in csvreader:
        # 过滤空行和无效行(检查Country Code是否为空)
        if not words[3]:
          continue
        c = Country()
        c.country_name = words[2]
        c.country_code = words[3]
        # 处理空值,转为None或0.0
        c.acc_to_clean_fuel = float(words[4]) if words[4] != '..' else None
        c.acc_to_elec = float(words[5]) if words[5] != '..' else None
        c.annual_freshwater_withdrawl = float(words[6]) if words[6] != '..' else None
        c.armed_forces_tot = int(words[7]) if words[7] != '..' else None
        c.expense_gdp = float(words[8]) if words[8] != '..' else None
        self.__list_countries.append(c)

额外说明

  • 如果需要给空值设置默认数值(比如0),只需把None替换为对应数值即可。
  • 若CSV中存在其他特殊格式的空值标记,可在判断条件中补充(如words[4] not in ['..', '', 'NA'])。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:25:00