【问题标题】:How do I fix this error: "ValueError: could not convert string to float: '-1,89E-09'"?如何修复此错误:“ValueError:无法将字符串转换为浮点数:'-1,89E-09'”?
【发布时间】:2017-02-01 14:08:31
【问题描述】:

我想通过读取这些数字并将其放入 y 列表中以科学计数法绘制数字。这是我的代码。

import matplotlib.pyplot as plt
import csv

x = []
y = []


with open('test1.txt','r') as csvfile:
     plots = csv.reader(csvfile, delimiter='\t')  
        for row in plots:
        x.append(float(row[0]))
        y.append(float(row[1]))


  plt.plot(x,y, label='20 Volt max with filter')
  plt.xlabel('time')
  plt.ylabel('voltage')
  plt.show()

.txt 文件如下所示:

0   -1,89E-09
0,001   -1,37E-08
0,002   -5,69E-08

错误是:

ValueError: could not convert string to float: '-1,89E-09'

【问题讨论】:

  • 请添加一个标签,表明您使用的语言。另外,您实际上还没有问过问题。
  • 我正在使用 Spyder (Python 3.5) 我的问题是我得到 ValueError: could not convert string to float: '-1,89E-09'
  • 该信息需要在问题中。添加一个“python”标签(可能有一个单独的“python3”标签),并在问题中显示确切的错误消息。 (我很确定我知道问题出在哪里,但我还不打算发布答案。)
  • 感谢您的回复。我试图编辑以使我的问题易于理解
  • 错误信息和您要问的问题应该在问题的正文中。我已经为你更新了。

标签: string python-3.5 scientific-notation


【解决方案1】:

在 Python 和许多其他语言中,标准的小数点分隔符是 .(句点)而不是 ,(逗号)。

来自维基百科上的Decimal Mark

1958 年,欧美 ISO 代表之间关于小数点正确表示的争议几乎使 ALGOL 计算机编程语言的发展停滞不前。 ALGOL 最终允许使用不同的小数点,但大多数计算机语言和标准数据格式(例如 C、Java、Fortran、级联样式表 (CSS))都指定了一个点。

您可以更改文本文件中使用的格式,也可以float(row[n].replace(",", "."))

【讨论】:

  • 对于图中的行:float(row[1].replace(",",".")) x.append(float(row[0])) y.append(float(row [1])) 但我得到语法错误我做错了什么
  • 您需要将float(row[n].replace(",", ".")) 分配给一个变量
  • >>> x.append(float(row[0].replace(",", "."))) >>> y.append(float(row[1].replace(",", ".")))>>> 谢谢你成功了!
  • @kevin 我很高兴它成功了!如果有帮助,您可以考虑accepting这个答案:)
猜你喜欢
  • 2020-09-12
  • 2021-06-21
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 2018-06-13
  • 2013-05-30
相关资源
最近更新 更多