【问题标题】:Cannot Convert String To Float无法将字符串转换为浮点数
【发布时间】:2016-11-09 20:41:08
【问题描述】:

我有一个 csv 文件,其中包含以下字符串形式的值:

'838.5',
'830.090027',
'820',
'827.559998',
'822.880005'

我正在像这样读取文件:

file = []
for line in open('project.csv'):
    our_data = line.split(",")

    data.append(our_data)

我尝试通过以下方式将这些转换为浮点数:

data = [float(x) for x in file]

但是当我运行程序时出现这个错误:

ValueError:无法将字符串转换为浮点数:.

如何在不编辑 csv 文件的情况下解决此问题?

【问题讨论】:

  • 你是如何阅读文件的?
  • file = [] for line in open('project.csv'): our_data = line.split(",") data.append(our_data)
  • 您能否将其添加到您的问题中。这将使所有可能试图帮助您的人更轻松。

标签: python string python-2.7 csv numbers


【解决方案1】:

给猫剥皮总是不止一种方法,但我会这样做:

# Read the entire contents of the file into a string (`numbers`).
# This includes newline characters and single-quotes.
with open('project.csv') as infile:
    numbers = infile.read()

# Then remove the newline characters and single-quotes
# (replace each with the empty string, thus removing them)
# resulting in a string with numbers separated by commas
# e.g., `123.3,45.9,39.1`
numbers = numbers.replace("'","").replace("\n","")

# Then create a new list by splitting the string on comma
# and converting each individual item to a float
numbers = [float(num) for num in numbers.split(',')]

注意事项:

  • 如果文件非常大,您可能希望逐行迭代而不是读取整个文件。

  • 如果输入文件可能包含格式错误,则必须更加小心以避免意外异常

【讨论】:

    【解决方案2】:

    原始文件包含引号和换行符 (\n),但您只是想摆脱换行符(但还没有完成)。首先你需要从split() 的输出中提取字符串(引号和数字),其次你需要去掉引号,然后使用 float(...) 将它们转换为浮点数:

    for line in open('project.csv'):
        our_data = line.split(",")
        print our_data
        our_data = our_data[0][1:-1]
        print our_data
        print float(our_data)
    

    会给你输出:

    ["'838.5'", '\n']
    838.5
    838.5
    ["'830.090027'", '\n']
    830.090027
    830.090027
    ["'820'", '\n']
    820
    820.0
    ["'827.559998'", '\n']
    827.559998
    827.559998
    ["'822.880005'"]
    822.880005
    822.880005
    

    【讨论】:

      【解决方案3】:

      您似乎对如何正确打开和拆分文件有些困惑。这应该有效。您的问题是您从文件中读取每一行,然后尝试拆分它。你实际附加到data 是这样的:

      ['838.5', ',']

      然后您尝试将其转换为浮点数,这当然意味着 Python 会引发错误。相反,读入整个文件,然后将其拆分。过滤掉任何不是数字的东西,然后将它们转换为浮点数:

      with open('project.csv') as file:
          file = file.readlines()
      
      file = [el[1:-1] for line in file for el in line.split(',')]
      floats = [float(el) for el in file if el]
      

      floats 的值:

      [838.5, 830.090027, 820.0, 827.559998, 822.880005]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多