【问题标题】:could not convert string to float:无法将字符串转换为浮点数:
【发布时间】:2019-03-03 15:48:58
【问题描述】:

这个函数没有正确地将文件转换为矩阵,当我运行代码时,我得到了错误消息: returnMat[index,:] = listFromLine[0:3]

ValueError: 无法将字符串转换为浮点数。

def fileToMatrix(filename):
        fr = open(filename)
        numberOfLines = len(fr.readlines())
        returnMat = np.zeros((numberOfLines,3))
        classLabelVector = []
        fr = open(filename)
        index = 0 
        for line in fr.readline():
            line = line.strip() #split in the end of the line
            listFromLine = line.split('\t') # split on tab and make list
            returnMat[index,:] = listFromLine[0:3]
            classLabelVector.append(int(listFromLine[-1]))
            index += 1

        return returnMat, classLabelVector



    if __name__ == '__main__':

        filename ="mydata.txt"
        returnMat,classLabelVector=fileToMatrix(filename)
        print(returnMat)

数据文件如下:

enter image description here

【问题讨论】:

  • 请将错误消息的完整堆栈跟踪作为文本包含在您的问题中。
  • @mkrieger1 完成
  • 您的数据是否包含任何数字较少的行或空行(即使它是所有其他行之后的最后一行)?
  • no所有行都有相关数据,不为空且为nan值

标签: python


【解决方案1】:

哈哈...错误就在这行:

for line in fr.readline():

我应该使用 readlines() 函数来读取 .txt 文件的所有行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多