Python读写excel的工具库很多,比如最耳熟能详的xlrd、xlwt,xlutils,openpyxl等。其中xlrd和xlwt库通常配合使用,一个用于读,一个用于写excel。xlutils结合xlrd可以达到修改excel文件目的。openpyxl可以对excel文件同时进行读写操作。

而说到数据预处理,pandas就体现除了它的强大之处,并且它还支持可读写多种文档格式,其中就包括对excel的读写。本文重点就是介绍pandas对excel数据集的预处理。

机器学习常用的模型对数据输入都是有要求的,多数机器学习算法最基本的要求是训练数据要转换成数值格式。当然,也有像决策树算法这种不需要转换为数值的算法,这里不做特例讨论。

pandas读取excel文件的函数是pandas.read_excel(),主要参数包括:

io : 读取的excel文档地址,

string, path object (pathlib.Path or py._path.local.LocalPath),

file-like object, pandas ExcelFile, or xlrd workbook. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file://localhost/path/to/workbook.xlsx

sheet_name : 读取的excel指定的sheet页

string, int, mixed list of strings/ints, or None, default 0

Strings are used for sheet names, Integers are used in zero-indexed sheet positions.

Lists of strings/integers are used to request multiple sheets.

Specify None to get all sheets.

str|int -> DataFrame is returned. list|None -> Dict of DataFrames is returned, with keys representing sheets.

Available Cases

  • Defaults to 0 -> 1st sheet as a DataFrame
  • 1 -> 2nd sheet as a DataFrame
  • “Sheet1” -> 1st sheet as a DataFrame
  • [0,1,”Sheet5”] -> 1st, 2nd & 5th sheet as a dictionary of DataFrames
  • None -> All sheets as a dictionary of DataFrames

header : 设置读取的excel第一行是否作为列名称

int, list of ints, default 0

Row (0-indexed) to use for the column labels of the parsed DataFrame. If a list of integers is passed those row positions will be combined into a MultiIndex. Use None if there is no header.

names :设置每列的名称,数组形式参数

   array-like, default None

List of column names to use. If file contains no header row, then you should explicitly pass header=None

index_col :设置读取的excel第一列是否作为行名称

   int, list of ints, default None

Column (0-indexed) to use as the row labels of the DataFrame. Pass None if there is no such column. If a list is passed, those columns will be combined into a MultiIndex. If a subset of data is selected with usecols, index_col is based on the subset.

usecols :执行需要读取的数据列,通常载入的excel包含不需要的列

    int or list, default None

  • If None then parse all columns,
  • If int then indicates last column to be parsed
  • If list of ints then indicates list of column numbers to be parsed
  • If string then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.

下满是一些pandas读取excel数据的示例:

将数据集写入excel文件:

>>> df_out = pd.DataFrame([('string1', 1),
... ('string2', 2),
... ('string3', 3)],
... columns=['Name', 'Value'])
>>> df_out
Name Value
0 string1 1
1 string2 2
2 string3 3
>>> df_out.to_excel('tmp.xlsx')

读取excel文件:

>>> pd.read_excel('tmp.xlsx')
Name Value
0 string1 1
1 string2 2
2 string3 3

参数index_col and header 都设置为None表示不读取excel的第一行和第一列作为标题和默认索引:

>>> pd.read_excel('tmp.xlsx', index_col=None, header=None)
0 1 2
0 NaN Name Value
1 0.0 string1 1
2 1.0 string2 2
3 2.0 string3 3

甚至可以专门制定列的格式:

>>> pd.read_excel('tmp.xlsx', dtype={'Name':str, 'Value':float})
Name Value
0 string1 1.0
1 string2 2.0
2 string3 3.0

下面是综合示例:读取text.xlsx文件的sheet1页,仅载入D:F列的数据。这里F列是类别标签,需要类别1和类别2转换为数字,应用于机器学习的输入建模。

import pandas as pd

def reader(path,sheet):
return pd.read_excel(path, sheet_name=sheet, usecols='D:F') trainrd = reader('text.xlsx','sheet1')
trainrd.head(5) #查看前5行数据
trainrd['x']=0 #新建一列x
trainrd.loc[trainrd['类别']=='类别1','x']=0 #将类别列的文字转换为数字
trainrd.loc[trainrd['类别']=='类别2','x']=1

机器学习之数据预处理,Pandas读取excel数据的更多相关文章

  1. pandas玩转excel-> (2)如何利用pandas读取excel数据文件

    import pandas as pd #将excel文件读到内存中,形成dataframe,并命名为peoplepeople=pd.read_excel('D:/python结果/task2/Peo ...

  2. Python的工具包[1] -> pandas数据预处理 -> pandas 库及使用总结

    pandas数据预处理 / pandas data pre-processing 目录 关于 pandas pandas 库 pandas 基本操作 pandas 计算 pandas 的 Series ...

  3. Python利用pandas处理Excel数据的应用

    Python利用pandas处理Excel数据的应用   最近迷上了高效处理数据的pandas,其实这个是用来做数据分析的,如果你是做大数据分析和测试的,那么这个是非常的有用的!!但是其实我们平时在做 ...

  4. 【python基础】利用pandas处理Excel数据

    参考:https://www.cnblogs.com/liulinghua90/p/9935642.html 一.安装第三方库xlrd和pandas 1:pandas依赖处理Excel的xlrd模块, ...

  5. [Pandas]利用Pandas处理excel数据

    Python 处理excel的第三包有很多,比如XlsxWriter.xlrd&xlwt.OpenPyXL.Microsoft Excel API等,最后综合考虑选用了Pandas. Pand ...

  6. 【Python自动化Excel】pandas处理Excel数据的基本流程

    这里所说的pandas并不是大熊猫,而是Python的第三方库.这个库能干嘛呢?它在Python数据分析领域可是无人不知.无人不晓的.可以说是Python世界中的Excel. pandas库处理数据相 ...

  7. java的poi技术读取Excel数据到MySQL

    这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 ...

  8. .NET读取Excel数据,提示错误:未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序

    解决.NET读取Excel数据时,提示错误:未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序的操作: 1. 检查本机是否安装Office Access,如果未安装去去h ...

  9. oledbdataadapter 读取excel数据时,有的单元格内容不能读出

    表现:excel中某列中,有的单元格左上角有绿色箭头标志,有的没有,c#编写读取程序,但是只能读取出带绿色箭头的单元格中的内容,其余不带的读取不到内容 原因:excel中单元格因为是文本格式而存储了数 ...

随机推荐

  1. FeignClient与RestTemplate的区别比较简单研究

    题外:个人觉得可能还没达到那种境界,还体会不到真正的实质性区别,就好比用HttpClient可以实现的用FeignClient同样可以实现,反之也是. JAVA 项目中接口调用怎么做 ? Httpcl ...

  2. 转载:做ArcEngine的二次开发出现“没有注册类别 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG)”

    转自:http://blog.sina.com.cn/s/blog_638e61a40100ynnc.html 出现这个问题主要是因为32位操作系统和64位操作系统存在兼容性问题. 解决方案: 1.鼠 ...

  3. NSLog 输出格式集合

    • %@ 对象 • %d, %i  整数 • %u  无符整形 • %f  浮点/双字 • %x, %X 二进制整数 • %o  八进制整数 • %zu size_t • %p  指针 • %e  浮 ...

  4. Sata win7 热插拔(AHCI)

    主板支持AHCI,把sata模式改成AHCI,在bios打开SATA热插拔开关 开启AHCI,需要修改注册表:HKEY_LOCAL_MACHINE\System\CurrentControlSet\S ...

  5. React个人学习笔记

    元素渲染 通过 ReactDOM.render() 方法渲染页面, 可以使用 ES6 class 来定义一个组件: 如何解析HTMl里面的空格: 1. 使用空格的 unicod 编码 : \u0020 ...

  6. [转]create a basic sql server 2005 trigger to send email alerts

    本文转自:http://blog.netnerds.net/2008/02/create-a-basic-sql-server-2005-trigger-to-send-e-mail-alerts/ ...

  7. Delphi中Frame的使用方法(1)

    Frame是组件面板上的第一个组件,但不是每个人都知道怎么用它,因为它不像Button和Label一样简单明了.实际上,Frame按钮只是打开一个Frame的列表,如果你没有创建任何的Frame,自然 ...

  8. CF(D. Fibonacci Sums)dp计数

    题目链接:http://codeforces.com/contest/126/problem/D 题意:一个数能够有多种由互不同样的斐波那契数组成的情况: 解法:dp,easy证明:每一个数通过贪心能 ...

  9. Android EditText 状态切换

    不可编辑状态 <EditText                     android:id="@+id/ed_newPwd"                     an ...

  10. windows下mysql中文乱码, 配置解决方法

    内容源自:windows下mysql中文乱码, 配置解决方法 解决方法:打开mysql安装目录,打开my.ini文件(如果只有my-default.ini文件,先将其改名为my.ini!!!) 修改内 ...