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
나는 이것에 혼란 스럽습니다. 스크립트를 사용하는 for 루프 대신 대화식 섹션에서 한 줄만 시도하면 다음과 같습니다.
>>> 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...]
잘 작동한다.
누구든지 이것에 대해 조금 설명 할 수 있습니까? 감사합니다.
분명히 일부 라인에는 유효한 float 데이터가 없습니다. 특히 일부 라인에는 id
float로 변환 할 수없는 텍스트 가 있습니다.
대화 형 프롬프트에서 시도 할 때 첫 번째 줄만 시도하는 것이므로 가장 좋은 방법은이 오류가 발생한 줄을 인쇄하는 것이며 잘못된 줄을 알 수 있습니다.
#!/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]
내 오류는 매우 간단했습니다. 데이터가 포함 된 텍스트 파일 의 마지막 줄에 공백 (보이지 않는) 문자가있었습니다.
As an output of grep, I had 45
instead of just 45
.
This error is pretty verbose:
ValueError: could not convert string to float: id
Somewhere in your text file, a line has the word id
in it, which can't really be converted to a number.
Your test code works because the word id
isn't present in line 2
.
If you want to catch that line, try this code. I cleaned your code up a tad:
#!/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]
Your data may not be what you expect -- it seems you're expecting, but not getting, floats.
A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:
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]
Perhaps your numbers aren't actually numbers, but letters masquerading as numbers?
In my case, the font I was using meant that "l" and "1" looked very similar. I had a string like 'l1919' which I thought was '11919' and that messed things up.
Check the number in the original csv file, to see if there is double quote on the numebers.
I solved the similar situation with basic technique using pandas. First load the csv or text file using pandas.It's pretty simple
data=pd.read_excel('link to the file')
Then set the index of data to the respected column that needs to be changed. For example, if your data has ID as one attribute or column, then set index to ID.
data = data.set_index("ID")
Then delete all the rows with "id" as the value instead of number using following command.
data = data.drop("id", axis=0).
Hope, this will help you.
참고URL : https://stackoverflow.com/questions/8420143/valueerror-could-not-convert-string-to-float-id
'IT TIP' 카테고리의 다른 글
가능한 한 쉽게 다형성을 설명하십시오. (0) | 2020.12.09 |
---|---|
file_get_contents ()가 UTF-8 문자를 분리합니다. (0) | 2020.12.09 |
data.table을 여러 열로 그룹화하는 방법은 무엇입니까? (0) | 2020.12.08 |
fmt.Println 대신 log.Println을 사용해야하는 이유는 무엇입니까? (0) | 2020.12.08 |
값에 의한 전달 및 이동이 잘못된 관용구를 구성합니까? (0) | 2020.12.08 |