值错误:无法将字符串转换为浮点数:id
我正在运行以下的Python脚本:
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f = open('data2.txt', 'r').readlines()
for i in range(0, len(f)-1):
l1 = f[i].split()
list1 = [float(x) for x in l1]
但是我遇到了这样的错误:
ValueError: could not convert string to float: id
这让我感到困惑。
当我在交互式环境中只尝试一行代码,而不是用脚本中的循环时:
from scipy import stats
import numpy as np
f = open('data2.txt','r').readlines()
l1 = f[1].split()
list1 = [float(x) for x in l1]
list1
# [5.3209183842, 4.6422726719, 4.3788135547]
它运行得很好。能不能简单解释一下这是为什么呢?
12 个回答
23
这个错误信息说得很详细:
ValueError: could not convert string to float: id
在你的文本文件的某个地方,有一行包含了单词 id
,这个单词不能被转换成数字。
你的测试代码能正常工作是因为在 line 2
中没有出现单词 id
。
如果你想找到那一行,可以试试这个代码。我稍微整理了一下你的代码:
#!/usr/bin/python
import os, sys
from scipy import stats
import numpy as np
for index, line in enumerate(open('data2.txt', 'r').readlines()):
w = line.split(' ')
l1 = w[1:8]
l2 = w[8:15]
try:
list1 = map(float, l1)
list2 = map(float, l2)
except ValueError:
print 'Line {i} is corrupt!'.format(i = index)'
break
result = stats.ttest_ind(list1, list2)
print result[1]
37
我的错误其实很简单:存放数据的文本文件最后一行有一些空格(看不见的)字符。
所以我用grep命令输出的时候,得到了45
,而不是单纯的45
。
71
显然,你的一些行数据不是有效的浮点数,特别是有些行包含了文本 id
,这些是无法转换成浮点数的。
当你在交互式提示中尝试时,你只是在处理第一行,所以最好的办法是打印出出现错误的那一行,这样你就能知道是哪一行出问题了,比如:
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]