【问题标题】:Could not convert string to float error while using csv files使用 csv 文件时无法将字符串转换为浮点错误
【发布时间】:2021-09-15 19:44:12
【问题描述】:

我正在尝试将我的 csv 文件的两个列加载到 python 中的数组中。但是我得到了:

ValueError: could not convert string to float: ''.

我已经附上了实现代码的 sn-ps 和我试图存储在数组中的 csv 文件。

import csv


col1 = []
col2 = []
path = r'C:\Users\angel\OneDrive\Documents\CSV_FILES_NV_LAB\1111 x 30.csv'
with open(path, "r") as f_in:
    reader = csv.reader(f_in)
    next(reader)  # skip headers

    for line in reader:
        col1.append(float(line[0]))
        col2.append(float(line[1]))

print(col1)
print(col2)

【问题讨论】:

  • 这能回答你的问题吗? ValueError: could not convert string to float: id
  • CSV 文件中有空行或包含空字段的行。
  • 正在读取的csv文件的sn-p在哪里?
  • 尝试使用col1.append( float(line[0]) if line[0] else 0.0 ) 而不是你所拥有的。为col2 做类似的事情。

标签: python csv valueerror


【解决方案1】:

CSV 文件中有哪些值?如果这些值无法转换为floats,您将获得ValueError。例如,如果您的 CSV 文件如下所示:

ColName,ColName2
abc,def
123,45.6
g,20

错误将在循环的第一次迭代中引发,因为 abc 无法转换为浮点数。但是,如果 CSV 文件中的所有值都是数字:

ColName, ColName2
1,2
123,45.6
100,20

不会引发错误。

如果 CSV 文件中有一些数字值和一些非数字值,则可以通过在循环中包含 try...except 块来省略包含非数字值的行:

for line in reader:
    try:
        float_1, float_2 = float(line[0]), float(line[1])
        
        # If either of the above conversions failed, the next two lines will not be reached
        col1.append(float_1)
        col2.append(float_2)

    except ValueError:
        continue  # Move on to next line
    

【讨论】:

    【解决方案2】:

    也许您忘记添加.split(',')?现在,line[0]line[1] 只需取行的第一个和第二个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-31
      • 2019-08-15
      • 2021-10-10
      • 2018-10-28
      相关资源
      最近更新 更多