python数据预处理for knn

机器学习实战 一书中第20页数据预处理,从文本中解析数据的程序。
 1 import numpy as np
 2 def dataPreProcessing(fileName):
 3     with open(fileName) as op:
 4         lines=op.readlines()
 5         # 返回值是list
 6         lineNumer=len(lines)
 7         # list长度即文件中的行数
 8         dataMatrix=np.zeros((lineNumer,3))
 9         # 初始化lineNumer行,3列的全0矩阵,注意双层括号
10         labelVector=[]
11         # 标记向量初始化,它在目前是一个空的list
12         index=0
13         # 索引,为了后面给数据矩阵和标记向量初始化用的
14         for line in lines:
15             line=line.strip()
16             # 去空格
17             temp=line.split('\t')
18             # 按换行符分割数据,返回list
19             dataMatrix[index,:]=temp[0:3]
20             # 切片操作,dataMatrix[a,b:c]后的方括号中第一个值表示矩阵行号(从0开始)
21             # 第二、三个参数代表从b开始,c结束,前开后闭,包含b不包含c的元素
22             # temp中的两个参数同理
23             # 将temp中的前3个值赋给dataMatrix
24             labelVector.append(int(temp[-1]))
25             # 将temp中的最后一个值赋给labelVector,注意强转类型,不强转取到的类型为string
26             index=index+1
27         return dataMatrix,labelVector
28 # arr=np.array([[0,1,2],[3,4,5],[6,7,8]])
29 # print(arr[2,:])
30 fileName='./datingTestSet2.txt'
31 # “/”:表示根目录,在windows系统下表示某个盘的根目录,如“E:\”;
32 # “./”:表示当前目录;(表示当前目录时,也可以去掉“./”,直接写文件名或者下级目录)
33 # “../”:表示上级目录。
34 a,b=dataPreProcessing(fileName)
35 print(a,b)
View Code

 



附:今晚很郁闷,pycharm启动慢得要死,Numpy又用不了,好不容易才用清华镜像把numpy升级到可用状态,期间pycharm卡死了好几次,ukylin的虚拟机更卡,气得我想把电脑砸了,以后有替代的ide了再也不用pycharm了


---------------------------------------------------------------------------------------
2020-02-15更新
读取txt文件中的数据
testArray=genfromtxt(fileName,delimiter="\t",dtype=str)
# 文件名、分隔符、读取的数据以什么类型返回
# print('testArray=\n',testArray)
# print(testArray.shape)
# print(testArray.dtype)
testLabels=testArray[:,3]
testLabels=testLabels.astype(int)
# 矩阵切片,取出所有行第3列,其中:表示所有行
print('testLabels\n',testLabels)
print(testLabels.shape)
testInfo=testArray[:,0:3]
# 读取每一行的前3列,这里的0:3是左闭右开区间
testInfo=testInfo.astype(float)
print('testInfo:\n',testInfo)

  今晚又重温了 “唐宇迪\1章Python科学计算库—numpy”课程系列中的 05-07三节内容,其中《课时07.Numpy矩阵基础》只看到了3'12''

posted @ 2019-01-03 00:31  飞向天边  阅读(446)  评论(0编辑  收藏  举报