无法将字符串转换为float:'x',Kmeans implementation python

2024-10-02 20:40:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试通过python中的kmeans实现获得一个架构索引。我把我的cvs文件转换成Tuple,但是当我尝试获取k means clusters时,得到以下错误:无法将字符串转换为浮动:x。在

这是我的代码:

def archCVS (filename): #Covert to CVS to Tuple
    fileHandelr = open(filename, "rt")
    lines= fileHandelr.readlines()
    fileHandelr.close()
    #del lines[0] #remove the header
    dataset=[]
    for line in lines:
        instance= lineToTuple(line)
        dataset.append(instance)
    return dataset

def lineToTuple(line): #Conver a comma separate string into tuple
    cleanLine=line.strip()
    cleanLine= cleanLine.replace('"', '')
    lineList=cleanLine.split(",")
    stringToNumbers(lineList)
    lineTuple=tuple(lineList)
    return lineTuple

def stringToNumbers(myList): #Convert string to numbers
    for i in range(len(myList)):
        if(isValidNumberString(myList[i])):
            myList[i]=float(myList[i])

def isValidNumberString(s): #Number verification 
    if len(s)==0:
        return False
    if len(s) > 1 and s[0]=="-":
        s=s[1:]
    for  c in s:
        if c not in "0123456789.":
            return False
    return True

def KmeasandShilo(X):
    kmeans_model =KMeans(n_clusters=2,random_state=10).fit(X)
    labels=kmeans_model.labels_
    Silho= metrics.silhouette_score(X,labels,metric='euclidean')
    return Silho

我得到这个错误

Error imagem

我能做什么?在


Tags: toinforlenreturnifdefline
1条回答
网友
1楼 · 发布于 2024-10-02 20:40:50

列表中包含科学格式的数字(e-05),所以这可能是问题的根源。您必须修改函数stringToNumbers。我建议使用

try:
  myList = map(float,myList)
except ValueError:
  print 'Error: in converting list = ',myList

相关问题 更多 >