温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

利用Python怎么将读取数据集消除空行

发布时间:2021-03-02 15:33:11 来源:亿速云 阅读:239 作者:戴恩恩 栏目:开发技术

这篇文章主要介绍了利用Python怎么将读取数据集消除空行,此处通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考价值,需要的朋友可以参考下:

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

如下所示:

# -*- coding: utf-8 -*-
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怎么将读取数据集消除空行的内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI