【问题标题】:how to fix ValueError :could not convert string to float: in Python如何修复 ValueError :无法将字符串转换为浮点数:在 Python 中
【发布时间】:2018-02-23 13:38:04
【问题描述】:

我有一个从 CSV 文件读取并检查记录是否满足条件的 python 脚本。

  • 如果是则系统显示结果
  • 如果没有,系统会根据错误引发异常。

csv 文件包含一个具有浮点值的文件,但其中一些记录可能没有任何值,因此将为空。

问题是如果单元格为空,系统会显示此 ValueError :

could not convert string to float: 

而不是我写的异常。

 raise Exception("this Record has empty value")
  • row[0]==> 日期类型 Date
  • row[10]==> 风速型浮子
  • row[11]==> 雾类型布尔

代码:

import csv

mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")

# read the first line in the opened file ==> Header
myfile.readline()


myreader=csv.reader(myfile,mydelimeter)
mywind,mydate=[],[]
minTemp, maxTemp = [],[]
fastwindspeed, fog=[],[]

'''
create a variable that handle values of the 3 fields ==> Date - fastest5secwindspeed - fog
 and display the result where  
     fog ==> Yes    and highest speed  more than 10.
'''
for row in myreader:
    try:
        if row[11] =="Yes":
            if float(row[10]) < 10.0:
                raise Exception( 'the wind speed  is below 10 mph in ' + row[0] )
            if row[10] in (None, ""):
                raise Exception("this Record has empty value")

            print(row[0],row[10],row[11])
    except Exception as e:
        print("{}".format(e))

myfile.close()

【问题讨论】:

  • 在尝试转换之前测试它是否为空。
  • 例如检查是否为空,见stackoverflow.com/questions/9573244/…
  • @ThierryLathuille 如果 row[10] in (None, ""): raise Exception("this Record has empty value")

标签: python csv readline


【解决方案1】:

您可以更改加注的顺序,同时您应该处理该列中非浮动的可能性:

import csv

mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")

# read the first line in the opened file ==> Header
myfile.readline()


myreader=csv.reader(myfile,mydelimeter)
mywind,mydate=[],[]
minTemp, maxTemp = [],[]
fastwindspeed, fog=[],[]

'''
create a variable that handle values of the 3 fields ==> Date - fastest5secwindspeed - fog
 and display the result where  
     fog ==> Yes    and highest speed  more than 10.
'''
for row in myreader:
    try:
        if row[11] =="Yes":
            if row[10] in (None, ""):
                raise Exception("this Record has empty value")
            try:
                if float(row[10]) < 10.0:
                    raise Exception( 'the wind speed  is below 10 mph in ' + row[0] )
            except ValueError:
                raise Exception('This Column expected to have a float has a non-float instead")

            print(row[0],row[10],row[11])
    except Exception as e:
        print("{}".format(e))

myfile.close()

【讨论】:

  • 谢谢,这是加薪顺序的问题
【解决方案2】:

我在项目工作期间也遇到过这个问题。我只是像下面这样:-

  if(len(row[10]) > 0):
      wind_speed = flot(row[10])

【讨论】:

    猜你喜欢
    • 2021-06-21
    • 2021-01-11
    • 2018-04-23
    • 2015-03-25
    • 2021-12-23
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多