Python读取数据集并消除数据中的空行方法

yipeiwu_com5年前Python基础

如下所示:

# -*- coding: utf-8 -*-
# @ author hulei 2016-5-3
from numpy import *
import operator
from os import listdir
 
import sys
reload(sys)
sys.setdefaultencoding('utf8')
 
# x,y=getDataSet_dz('iris.data.txt',4)
 
def getDataSet(filename,numberOfFeature):  #将数据集读入内存 
 fr = open(filename)
 numberOfLines = len(fr.readlines())   #get the number of lines in the file file.readlines()是把文件的全部内容读到内存,并解析成一个list
 returnMat = zeros((numberOfLines,numberOfFeature))  #prepare matrix to return 3代表数据集中特征数目###
 classLabelVector = []      #prepare labels return 
 fr = open(filename)
 index = 0
 for line in fr.readlines():
  line = line.strip()     #strip() 参数为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
  listFromLine = line.split(',')   #split 以什么为标准分割一次 分成数组中的每个元素
  returnMat[index,:] = listFromLine[0:numberOfFeature] 
  #classLabelVector.append(int(listFromLine[-1])) #append() 方法向列表的尾部添加一个新的元素
  if listFromLine[-1] == 'Iris-setosa' :
   classLabelVector.append(1)
  elif listFromLine[-1] == 'Iris-versicolor' :
   classLabelVector.append(2)
  else:
  #elif listFromLine[-1] == 'Iris-virginica' :
   classLabelVector.append(3)
  index += 1
 return returnMat,classLabelVector
 
def getDataSet_dz(filename,numberOfFeature): #改进版,可以消除数据中的空白行
 numberOfLines = 0
 mx = []  #将数据集 去除空行后存入
 fr = open(filename)
 for line in fr.readlines():  
  line = line.strip() 
  if line != '' : #去除空白行 
   numberOfLines+=1
   mx.append( line.split(',') )
 returnMat = zeros((numberOfLines,numberOfFeature))
 classLabelVector = [] 
 for index in range(numberOfLines) :
  returnMat[index,:] = mx[index][0:numberOfFeature] 
  if mx[index][-1] == 'Iris-setosa' :
   classLabelVector.append(1)
  elif mx[index][-1] == 'Iris-versicolor' :
   classLabelVector.append(2)
  else:
  #elif listFromLine[-1] == 'Iris-virginica' :
   classLabelVector.append(3)
 return returnMat,classLabelVector

以上这篇Python读取数据集并消除数据中的空行方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解析Python中的eval()、exec()及其相关函数

刚好前些天有人提到eval()与exec()这两个函数,所以就翻了下Python的文档。这里就来简单说一下这两个函数以及与它们相关的几个函数,如globals()、locals()和co...

python socket网络编程之粘包问题详解

python socket网络编程之粘包问题详解

一,粘包问题详情 1,只有TCP有粘包现象,UDP永远不会粘包 你的程序实际上无权直接操作网卡的,你操作网卡都是通过操作系统给用户程序暴露出来的接口,那每次你的程序要给远程发数据时,...

Python备份目录及目录下的全部内容的实现方法

本来是想写一个东西可以直接调用TortoiseSVN保存当前代码到一个分枝下的。 可惜调用SVN的部分还在研究。就先写了目录拷贝的部分。 如果有喜欢研究Python的童鞋愿意提供想法或者...

Python OrderedDict的使用案例解析

这篇文章主要介绍了Python OrderedDict的使用案例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 很多人认为python...

Python实现KNN邻近算法

简介 邻近算法,或者说K最近邻(kNN,k-NearestNeighbor)分类算法是数据挖掘分类技术中最简单的方法之一。所谓K最近邻,就是k个最近的邻居的意思,说的是每个样本都可以用...