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设计】。

相关文章

Windows安装Python、pip、easy_install的方法

Windows安装Python、pip、easy_install的方法

安装Python 下载Python安装包 https://www.python.org/downloads/ 图形化安装 选择安装位置 这里安装至D:\Program Files (x8...

使用tqdm显示Python代码执行进度功能

使用tqdm显示Python代码执行进度功能

在使用Python执行一些比较耗时的操作时,为了方便观察进度,通常使用进度条的方式来可视化呈现。Python中的tqdm就是用来实现此功能的。 先来看看tqdm的进度条效果:  ...

python遍历文件夹并删除特定格式文件的示例

复制代码 代码如下:#!/usr/bin/python# -*- coding: utf-8 -*- import os def del_files(path):  ...

python字符串加密解密的三种方法分享(base64 win32com)

1. 最简单的方法是用base64: 复制代码 代码如下:import base64 s1 = base64.encodestring('hello world')s2 = base64...

解决pycharm最左侧Tool Buttons显示不全的问题

解决pycharm最左侧Tool Buttons显示不全的问题

问题描述如下: 解决方案如下: 下图中字体调整为18及以上 效果如下: 以上这篇解决pycharm最左侧Tool Buttons显示不全的问题就是小编分享给大家的全部内容了,希望能...