ValueError:无法将字符串转换为float:id [英] ValueError: could not convert string to float: id

查看:387
本文介绍了ValueError:无法将字符串转换为float:id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #!/ usr / bin / python 

导入os,sys
从scipy导入统计
导入numpy为np
$ bf = open('data2.txt','r')。readlines()$ b $ (0,N):
w = f [i] .split()
l1 = w [1:8]
l2 = w [8:15]
list1 = [float(x)for x in l1]
list2 = [float(x)for x in l2]
result = stats。 ttest_ind(list1,list2)
print result [1]



  ValueError:无法将字符串转换为float:id 

我对此感到困惑。
当我在交互式部分只使用一行时,而不是使用脚本循环:

 >> ;> from scipy import stats 
>>> import numpy as np
>>> f = open('data2.txt','r')。readlines()
>>> w = f [1] .split()
>>> l1 = w [1:8]
>>> l2 = w [8:15]
>>> list1 = [float(x)for x in l1]
>>> list1
[5.3209183842,4.6422726719,4.3788135547,5.9299061614,5.9331108706,5.0287087832,4.57 ...]



<我很好。



任何人都可以解释一下这个吗?
thx

解决方案

显然有些行没有有效的浮点数据, c $ c> id 不能转换为浮点数。

当您在交互式提示符中尝试时,您只尝试第一行,所以最好的方法是打印出现此错误的行,您将知道错误的行例如

 #!/ usr / bin / python 

import os,sys
from scipy import stats
import numpy as np
$ bf = open('data2.txt','r')。readlines()
N = len(f)-1
为范围(0,N):
w = f [i] .split()
l1 = w [1:8]
l2 = w [8:15] $
list1 = [float(x)for x in l1]
list2 = [float(x)for x in l2]
除ValueError,e:
打印错误,e,在线,我$ b $结果= stats.ttest_ind(list1,list2)
打印结果[1]


I'm running the following python script:

#!/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]
    list1=[float(x) for x in l1]
    list2=[float(x) for x in l2]
    result=stats.ttest_ind(list1,list2)
    print result[1]

However I got the errors like:

ValueError: could not convert string to float: id

I'm confused by this. When I try this for only one line in interactive section, instead of for loop using script:

>>> from scipy import stats
>>> import numpy as np
>>> f=open('data2.txt','r').readlines()
>>> w=f[1].split()
>>> l1=w[1:8]
>>> l2=w[8:15]
>>> list1=[float(x) for x in l1]
>>> list1
[5.3209183842, 4.6422726719, 4.3788135547, 5.9299061614, 5.9331108706, 5.0287087832, 4.57...]

I works well.

Can anyone explain a little bit about this? thx

解决方案

Obviously some of your lines don't have valid float data, specifically some line have text id which can't be converted to float.

When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.

#!/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]

这篇关于ValueError:无法将字符串转换为float:id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆