在数据分析过程中,很多时候需要从数据表中提取出相应的数据,而这么做的前提是需要先“索引”出这一部分数据。虽然通过 Python 提供的索引操作符"[]"和属性操作符"."可以访问 Series 或者 DataFrame 中的数据,但这种方式只适应与少量的数据,为了解决这一问题,Pandas 提供了两种类型的索引方式来实现数据的访问。

本节就来讲解一下,如何在 Pandas 中使用 loc 函数和 iloc 函数。两种函数说明如下:

方法名称 说明
.loc[] 基于标签索引选取数据
.iloc[] 基于整数索引选取数据

.loc[]

df.loc[] 只能使用标签索引,不能使用整数索引。当通过标签索引的切片方式来筛选数据时,它的取值前闭后闭,也就是只包括边界值标签(开始和结束)。

.loc[] 具有多种访问方法,如下所示:

  • 一个标量标签
  • 标签列表
  • 切片对象
  • 布尔数组

loc[] 接受两个参数,并以','分隔。第一个位置表示行,第二个位置表示列。示例如下:

  1. import numpy as np
  2. import pandas as pd
  3. #创建一组数据
  4. data = {'name': ['John', 'Mike', 'Mozla', 'Rose', 'David', 'Marry', 'Wansi', 'Sidy', 'Jack', 'Alic'],
  5. 'age': [20, 32, 29, np.nan, 15, 28, 21, 30, 37, 25],
  6. 'gender': [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
  7. 'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
  8. label = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  9. df = pd.DataFrame(data, index=label)
  10. print(df)
  11. #对行操作
  12. print(df.loc['a':'d',:]) #等同于df.loc['a':'d']

输出结果:

    name   age  gender isMarried
a   John  20.0       0       yes
b   Mike  32.0       0       yes
c  Mozla  29.0       1        no
d   Rose   NaN       1       yes
e  David  15.0       0        no
f  Marry  28.0       1        no
g  Wansi  21.0       0        no
h   Sidy  30.0       0       yes
i   Jack  37.0       1        no
j   Alic  25.0       1        no
#从a到d,切记包含d
    name   age  gender isMarried
a   John  20.0       0       yes
b   Mike  32.0       0       yes
c  Mozla  29.0       1        no
d   Rose   NaN       1       yes

对列进行操作,示例如下:

  1. import numpy as np
  2. import pandas as pd
  3. #创建一组数据
  4. data = {'name': ['John', 'Mike', 'Mozla', 'Rose', 'David', 'Marry', 'Wansi', 'Sidy', 'Jack', 'Alic'],
  5. 'age': [20, 32, 29, np.nan, 15, 28, 21, 30, 37, 25],
  6. 'gender': [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
  7. 'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
  8. label = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  9. df = pd.DataFrame(data, index=label)
  10. print(df.loc[:,'name'])

输出结果:

a     John
b Mike
c Mozla
d Rose
e David
f Marry
g Wansi
h Sidy
i Jack
j Alic
Name: name, dtype: object

对行和列同时操作,示例如下:

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(8, 4),
  4. index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D'])
  5. print(df.loc[['a','b','f','h'],['A','C']])

输出如下:

          A         C
a 1.168658 0.008070
b -0.076196 0.455495
f 1.224038 1.234725
h 0.050292 -0.031327

布尔值操作,示例如下:

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(4, 4),index = ['a','b','c','d'], columns = ['A', 'B', 'C', 'D'])
  4. #返回一组布尔值
  5. print(df.loc['b']>0)

输出结果:

A     True
B     True
C    False
D     True
Name: b, dtype: bool

.iloc[]

df.iloc[] 只能使用整数索引,不能使用标签索引,通过整数索引切片选择数据时,前闭后开(不包含边界结束值)。同 Python 和 NumPy 一样,它们的索引都是从 0 开始。

.iloc[] 提供了以下方式来选择数据:

  • 1) 整数索引
  • 2) 整数列表
  • 3) 数值范围

示例如下:

  1. data = {'name': ['John', 'Mike', 'Mozla', 'Rose', 'David', 'Marry', 'Wansi', 'Sidy', 'Jack', 'Alic'],
  2. 'age': [20, 32, 29, np.nan, 15, 28, 21, 30, 37, 25],
  3. 'gender': [0, 0, 1, 1, 0, 1, 0, 0, 1, 1],
  4. 'isMarried': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
  5. label = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  6. df = pd.DataFrame(data, index=label)
  7. print(df)
  8. print(df.iloc[2:,])

输出结果:

    name   age  gender isMarried
a John 20.0 0 yes
b Mike 32.0 0 yes
c Mozla 29.0 1 no
d Rose NaN 1 yes
e David 15.0 0 no
f Marry 28.0 1 no
g Wansi 21.0 0 no
h Sidy 30.0 0 yes
i Jack 37.0 1 no
j Alic 25.0 1 no name Mozla
age 29
gender 1
isMarried no
Name: c, dtype: object

再看一组示例:

  1. import pandas as pd
  2. import numpy as np
  3. df = pd.DataFrame(np.random.randn(8, 4), columns = ['A', 'B', 'C', 'D'])
  4. print df.iloc[[1, 3, 5], [1, 3]]
  5. print df.iloc[1:3, :]
  6. print df.iloc[:,1:3]

输出结果:

          B         D
1 0.773595 -0.206061
3 -1.740403 -0.464383
5 1.046009 0.606808 A B C D
1 -0.093711 0.773595 0.966408 -0.206061
2 -1.122587 -0.135011 0.546475 -0.551403 B C
0 0.623488 3.328406
1 0.773595 0.966408
2 -0.135011 0.546475
3 -1.740403 -0.869073
4 0.591573 -1.463275
5 1.046009 2.330035
6 -0.266607 0.873971
7 -1.059625 -0.405340

pandas之loc/iloc操作的更多相关文章

  1. Pandas:loc iloc ix用法

    参考:Pandas中关于 loc \ iloc \ ix 用法的理解 相同点 使用形式都是 df.xxx[ para1 , para2 ] #xxx表示loc iloc ix#df表示一个DataFr ...

  2. pandas的loc, iloc, ix的操作

    参考: https://blog.csdn.net/xw_classmate/article/details/51333646 1. loc——通过行标签索引行数据 2. iloc——通过行号获取行数 ...

  3. Pandas的 loc iloc ix 区别

    先看代码: In [46]: import pandas as pd In [47]: data = [[1,2,3],[4,5,6]] In [48]: index = [0,1] In [49]: ...

  4. python pandas 中 loc & iloc 用法区别

    转自:https://blog.csdn.net/qq_21840201/article/details/80725433 ### 随机生DataFrame 类型数据import pandas as ...

  5. pandas 定位 loc,iloc,ix

    In [114]: df Out[114]: A B C D 2018-06-30 0.318501 0.613145 0.485612 0.918663 2018-07-31 0.614796 0. ...

  6. Pandas之loc\iloc\ix

    ---------------------------------------------------------------------------------------------------- ...

  7. pandas 选取数据 修改数据 loc iloc []

    pandas选取数据可以通过 loc iloc  [] 来选取 使用loc选取某几列: user_fans_df = sample_data.loc[:,['uid','fans_count']] 使 ...

  8. python pandas(ix & iloc &loc)

    python pandas(ix & iloc &loc) loc——通过行标签索引行数据 iloc——通过行号索引行数据 ix——通过行标签或者行号索引行数据(基于loc和iloc ...

  9. pandas数据分析API常用操作

    1.导入数据 df = pd.read_csv( # 该参数为数据在电脑中的路径,可以不填写 filepath_or_buffer='/Users/Weidu/Desktop/sz000002.csv ...

  10. Pandas中Loc用法总结

    摘自:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html 具体用法,假设数据源为: > ...

随机推荐

  1. 在CentOS下安装nginx+php环境

    一.nginx 安装 1. 在nginx官网下载nginx源码 提供一个nginx官网下载地址: http://nginx.org/download/nginx-1.12.2.tar.gz 注意:请先 ...

  2. GPS时钟之户外防水防雷细节

    GPS时钟之户外防水防雷细节------专业LED时钟厂家![点击进入] GPS的脆弱性: 由于在GPS设计时,干扰环境下的工作能力不是优先考虑的因素,它只是作为一种导航的辅助工具,而不是用于精确制导 ...

  3. 关于uniapp的事件监听,使用uni.$once和uni.$on导致的重复监听

    最近写项目的时候遇到个问题,就是在使用uniapp的事件监听器时出现重复监听问题.一开始我是用的uni.$on去监听事件,然后出现了重复的触发监听.百度了下,官方提示单次触发的建议使用uni.$onc ...

  4. HTML第四章作业

    学生实践4.1.3 1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8" ...

  5. DNS服务学习笔记

    1.基本概念 ​ DNS(Domain Name System)域名系统,在TCP/IP网络中有非常重要的地位,能够提供域名与IP地址的解析服务. ​ DNS是一个分布式数据库,命名系统采用层次的逻辑 ...

  6. CF1430

    CF1430 那个博客搭好遥遥无期. A: 看代码. #include<bits/stdc++.h> using namespace std; int main() { int t;sca ...

  7. RKO组——冲刺随笔(1)

    这个作业属于哪个课程 至诚软工实践F班 这个作业要求在哪里 第五次团队作业:项目冲刺 这个作业的目标 记录冲刺计划.要求包括当天会议照片.会议内容以及项目燃尽图(项目进度) 1.昨日进展 小组成员讨论 ...

  8. 自定义配置Springboot内嵌的tomcat

    两种方法都可以:例子:在tomcat里添加MIME类型,application/wasm 1. import org.springframework.boot.web.embedded.tomcat. ...

  9. 使用scrollIntoView 使某元素滚动到指定位置

    var el = document.getElementById('A'); el.scrollIntoView('true'); 知识: element.scrollIntoView(); // 使 ...

  10. Windows10电源选项:睡眠、休眠、启用快速启动

    参考链接: http://www.dnpz.net/diannaozhishi/2223.html http://www.cfan.com.cn/2018/0118/130151.shtml 在介绍w ...