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实现画五角星和螺旋线的示例

python实现画五角星和螺旋线的示例

如下所示: # -*- coding:UTF-8 -*- __author__ = "zhangguodong" __time__ = "2017.11.16" import t...

利用Python获取赶集网招聘信息前篇

如何获取一个网站的相关信息,获取赶集网的招聘信息,本文为大家介绍利用python获取赶集网招聘信息的关键代码,供大家参考,具体内容如下 import re import urllib...

Python中文件的读取和写入操作

从文件中读取数据 读取整个文件 这里假设在当前目录下有一个文件名为'pi_digits.txt'的文本文件,里面的数据如下: 3.1415926535 8979323846 2643...

基于Python开发chrome插件的方法分析

基于Python开发chrome插件的方法分析

本文实例讲述了基于Python开发chrome插件的方法。分享给大家供大家参考,具体如下: 谷歌Chrome插件是使用HTML、JavaScript和CSS编写的。如果你之前从来没有写过...

python的依赖管理的实现

主流开发语言的包管理工具一般都是支持依赖管理的,比如PHP的composer、Java的mvn。 对于python来说又该如何管理依赖呢? pip基本用法 python还不错,它提供了...