2011-12-07 111 views
30

我運行以下Python腳本:ValueError異常:無法將字符串轉換爲float: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] 
    list1=[float(x) for x in l1] 
    list2=[float(x) for x in l2] 
    result=stats.ttest_ind(list1,list2) 
    print result[1] 

但是我得到了這樣的錯誤:

ValueError: could not convert string to 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

回答

27

顯然你的一些線路沒有有效的float數據,特別是一些線路上有文字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] 
+6

這有助於捕獲csv文件中的空字符串。 –

7

此錯誤是相當詳細:在文本文件中

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] 
3

您的數據可能不是您所期望的 - 看起來您期待的是,但沒有獲得浮動。

搞清楚一個簡單的解決方案,這種情況是添加一個try /除了for循環:

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: 
     # report the error in some way that is helpful -- maybe print out i 
    result=stats.ttest_ind(list1,list2) 
    print result[1] 
12

我的錯誤是非常簡單的:包含數據的文本文件,有一些空間(所以不可見)字符在最後一行。
作爲grep的輸出,我有45 而不是隻有45

經典的愚蠢的事情,讓你浪費時間。 :-)

+1

空格和製表符是可見的;)行尾和類似符號不是,例如,字符'\ n','\ r'。 –

0

也許你的數字不是實際的數字,而是字母僞裝成數字?

就我而言,我使用的字體意味着「l」和「1」看起來非常相似。我有一個像'l1919'這樣的字符串,我認爲它是'11919',這讓事情變得很糟糕。

相關問題