【发布时间】: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)
数据文件如下:
【问题讨论】:
-
请将错误消息的完整堆栈跟踪作为文本包含在您的问题中。
-
@mkrieger1 完成
-
您的数据是否包含任何数字较少的行或空行(即使它是所有其他行之后的最后一行)?
-
no所有行都有相关数据,不为空且为nan值
标签: python