上一篇文章中,我重点讲述了使用df.loc[]方法获取excel表格中的数据。本文中,我将继续这个话题,如何使用iloc[]方法获取数据。iloc是根据position获取的,pandas读取excel后会像数学坐标轴一样,将每个单元格进行标记。左端最上角的单元格定义为原点(0,0),从上往下依次是(1,0),(2,0)…;从左往右依次是(0,1),(0,2),(0,3)…。这样每一个单元格就可以被唯一的一个坐标所确定。通过调用help(df.iloc[])可以得知,该方法支持以下输入:
Purely integer-location based indexing for selection by position. | | ``.iloc[]`` is primarily integer position based (from ``0`` to | ``length-1`` of the axis), but may also be used with a boolean | array. | | Allowed inputs are:- An integer, e.g. ``5``. | - A list or array of integers, e.g. ``[4, 3, 0]``. # 列表 | - A slice object with ints, e.g. ``1:7``. # 切片 | - A boolean array. # 判断型boolean | - A ``callable`` function with one argument # 仅有一个参数的函数
下面我将重点对前三个举例讲解(其余的会安排出单独的章节):
>>> import pandas as pd>>> df = pd.read_excel(r'D:myExcel1.xlsx', 'Sheet1')>>> df name math science0 bob 23 121 millor 32 322 jiken 61 893 tom 34 944 json 83 125 dela 96 676 rison 90 34# 查询单行。列表第一个参数表示行,第二个表示列>>> df.iloc[0]name bobmath 23science 12Name: 0, dtype: object# 查询单列,行用切片表示,:前后无值表示所有行>>> df.iloc[:,0]0 bob1 millor2 jiken3 tom4 json5 dela6 risonName: name, dtype: object# 使用列表查询指定的某些完整行,>>> df.iloc[[1,3,5]] name math science1 millor 32 323 tom 34 945 dela 96 67# 使用切片查询第1,2行第0列的数据>>> df.iloc[1:3, [0]] name1 millor2 jiken
以上就是iloc[]的基本用法,接受单个数值,数值列表以及切片。哈哈,如果您对pandas有兴趣,欢迎关注我的公众号:python小工具。还有福利呢