在数据分析过程中,很多时候需要从数据表中提取出相应的数据,而这么做的前提是需要先“索引”出这一部分数据。虽然通过 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. Leetcode 199

    199. Binary Tree Right Side View Given the root of a binary tree, imagine yourself standing on the r ...

  2. char和int的类型转换

    char类型是16位的,底层采用unicode编码保存.char类型是可以直接赋值给int类型的,因为是16位到32位低到高.举个例子比如int i='1';打印i的值是49.char类型跟int类型 ...

  3. 解决office提示您的许可证不是正版的问题

    https://blog.csdn.net/d_pcb66/article/details/125339872?spm=1001.2101.3001.6650.4&utm_medium=dis ...

  4. VUE-使用touchstart、touchmove、touchend实现拖拽卡片列表,实现更新排序功能

    感谢本文参考地址,原文解析更加清晰如有需要请移步:https://blog.csdn.net/weixin_40400844/article/details/114849253 怕原链接失效,将代码拷 ...

  5. scrcpy

    捕获配置 缩小尺寸 有时,以较低的清晰度镜像 Android 设备以提高性能很有用. 将宽度和高度限制为某个值(例如 1024): scrcpy --max-size 1024 scrcpy -m 1 ...

  6. Python笔记(4)——元组(Python编程:从入门到实践)

    元组 1. 元组:不可变的列表.元组一经创建不能被修改. 2. 表示:用圆括号()来表示,并用逗号来分隔其中的元素.可通过索引访问其元素. 3. 访问:访问列表元素,指出元组的名称,再指出元素的索引, ...

  7. NOIP2010普及组

    T2]接水问题 有一些小细节,比如如果最小值存在多个,比如最后还需要一个完全结束的最大值 #include<iostream> #include<cstring> #inclu ...

  8. 设计模式 (Design Pattern)C# -- 简介

    简介 设计模式(Design Pattern)是对面向对象设计中反复出现的问题的解决方案. 设计模式代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用. 设计模式是软件开发人员在软件开发过程 ...

  9. VUE项目中检测网页滑动注意事项

    一.this.$nextTick(function () {             window.addEventListener('scroll', this.onScroll, true)   ...

  10. vue项目启动报错问题解决. Module build failed: Error: Node Sass does not yet support your current environment

    导入vue项目后,启动报错,异常如下: 1 error in ./src/pages/home.vue 2 Module build failed: Error: Node Sass does not ...