如何修复此错误:" ValueError:无法将字符串转换为浮点数:' -1,89E-09'"?

时间:2016-09-23 16:23:19

标签: string python-3.5 scientific-notation

我想通过阅读并将这些数字放在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'

1 个答案:

答案 0 :(得分:0)

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

来自维基百科上的Decimal Mark

  

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

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