详解pandas中iloc, loc和ix的区别和联系


Posted in Python onMarch 09, 2020

Pandas库十分强大,但是对于切片操作iloc, loc和ix,很多人对此十分迷惑,因此本篇博客利用例子来说明这3者之一的区别和联系,尤其是iloc和loc。

对于ix,由于其操作有些复杂,我在另外一篇博客专门详细介绍ix。

首先,介绍这三种方法的概述:

  • loc gets rows (or columns) with particular labels from the index. loc从索引中获取具有特定标签的行(或列)。这里的关键是:标签。标签的理解就是name名字。
  • iloc gets rows (or columns) at particular positions in the index (so it only takes integers). iloc在索引中的特定位置获取行(或列)(因此它只接受整数)。这里的关键是:位置。位置的理解就是排第几个。
  • ix usually tries to behave like loc but falls back to behaving like iloc if a label is not present in the index. ix通常会尝试像loc一样行为,但如果索引中不存在标签,则会退回到像iloc一样的行为。(这句话有些绕口,没关系,不明白可以看这里)

接下来,举几个例子说明:

1 loc

其实,对于loc始终坚持一个原则:loc是基于label进行索引的!

import pandas as pd
df1 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=[0, 1, 2], columns=['a','b','c'])
df2 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=['e', 'f', 'g'], columns=['a','b','c'])
print(df1)
print(df2)
'''
df1:
  a b c
0 1 2 3
1 4 5 6
2 7 8 9
df2:
  a b c
e 1 2 3
f 4 5 6
g 7 8 9
'''
 
# loc索引行,label是整型数字
print(df1.loc[0])
'''
a  1
b  2
c  3
Name: 0, dtype: int64
'''
 
# loc索引行,label是字符型
print(df2.loc['e'])
'''
a  1
b  2
c  3
Name: 0, dtype: int64
'''
# 如果对df2这么写:df2.loc[0]会报错,因为loc索引的是label,显然在df2的行的名字中没有叫0的。
print(df2.loc[0])
'''
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>
'''
 
# loc索引多行数据
print(df1.loc[1:])
'''
  a b c
1 4 5 6
2 7 8 9
'''
 
# loc索引多列数据
print(df1.loc[:,['a', 'b']])
'''
  a b
0 1 2
1 4 5
2 7 8
'''
# df1.loc[:,0:2]这么写报错, 因为loc索引的是label,显然在df1的列的名字中没有叫0,1和2的。
print(df1.loc[:,0:2])
'''
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>
'''
 
# locs索引某些行某些列
print(df1.loc[0:2, ['a', 'b']])
'''
  a b
0 1 2
1 4 5
2 7 8
'''

2 iloc

其实,对于iloc始终坚持一个原则:iloc是基于position进行索引的!

import pandas as pd
df1 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=[0, 1, 2], columns=['a','b','c'])
df2 = pd.DataFrame(data= [[1, 2, 3],[4, 5, 6], [7, 8, 9]], index=['e', 'f', 'g'], columns=['a','b','c'])
print(df1)
print(df2)
'''
df1:
  a b c
0 1 2 3
1 4 5 6
2 7 8 9
df2:
  a b c
e 1 2 3
f 4 5 6
g 7 8 9
'''
# iloc索引行,label是整型数字
print(df1.iloc[0])
'''
a  1
b  2
c  3
Name: 0, dtype: int64
'''
 
# iloc索引行,label是字符型。如果按照loc的写法来写应该是:df2.iloc['e'],显然这样报错,因为iloc不认识label,它是基于位置的。
print(df2.iloc['e'])
'''
TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [e] of <class 'str'>
'''
# iloc索引行,label是字符型。正确的写法应该如下:
# 也就说,不论index是什么类型的,iloc只能写位置,也就是整型数字。
print(df2.iloc[0])
'''
a  1
b  2
c  3
Name: e, dtype: int64
'''
 
# iloc索引多行数据
print(df1.iloc[1:])
'''
  a b c
1 4 5 6
2 7 8 9
'''
 
# iloc索引多列数据
# 如果如下写法,报错。
print(df1.iloc[:,['a', 'b']])
'''
TypeError: cannot perform reduce with flexible type
'''
# iloc索引多列数据, 正确写法如下:
print(df1.iloc[:,0:2])
'''
  a b
0 1 2
1 4 5
2 7 8
'''
 
# iloc索引某些行某些列
print(df1.iloc[0:2, 0:1])
'''
  a
0 1
1 4
'''

3 ix

ix的操作比较复杂,在pandas版本0.20.0及其以后版本中,ix已经不被推荐使用,建议采用iloc和loc实现ix。

如有对ix的使用比较感兴趣的朋友可以参考这篇博客。

到此这篇关于详解pandas中iloc, loc和ix的区别和联系的文章就介绍到这了,更多相关pandas iloc loc ix内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python通过邮件服务器端口发送邮件的方法
Apr 30 Python
一篇文章快速了解Python的GIL
Jan 12 Python
Python 创建空的list,以及append用法讲解
May 04 Python
Python pygorithm模块用法示例【常见算法测试】
Aug 16 Python
Python实现二叉树的常见遍历操作总结【7种方法】
Mar 06 Python
pandas.cut具体使用总结
Jun 24 Python
浅谈Python2之汉字编码为unicode的问题(即类似\xc3\xa4)
Aug 12 Python
面向对象学习之pygame坦克大战
Sep 11 Python
python飞机大战pygame游戏框架搭建操作详解
Dec 17 Python
python矩阵运算,转置,逆运算,共轭矩阵实例
May 11 Python
浅谈Python协程
Jun 17 Python
浅谈Python里面None True False之间的区别
Jul 09 Python
pandas中ix的使用详细讲解
Mar 09 #Python
Python unittest 自动识别并执行测试用例方式
Mar 09 #Python
python爬虫开发之urllib模块详细使用方法与实例全解
Mar 09 #Python
在Python IDLE 下调用anaconda中的库教程
Mar 09 #Python
python shell命令行中import多层目录下的模块操作
Mar 09 #Python
使用Python获取当前工作目录和执行命令的位置
Mar 09 #Python
python爬虫开发之Request模块从安装到详细使用方法与实例全解
Mar 09 #Python
You might like
PHP生成静态页
2006/11/25 PHP
PHP实现无限极分类的两种方式示例【递归和引用方式】
2019/03/25 PHP
5 cool javascript apps
2007/03/24 Javascript
jquery ui dialog里调用datepicker的问题
2009/08/06 Javascript
js预载入和JavaScript Image()对象使用介绍
2011/08/28 Javascript
使用jquery解析XML的方法
2014/09/05 Javascript
JavaScript中的方法调用详细介绍
2014/12/30 Javascript
JS简单限制textarea内输入字符数量的方法
2015/10/14 Javascript
原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法
2016/08/05 Javascript
js实现旋转木马效果
2017/03/17 Javascript
javascript 面向对象实战思想分享
2017/09/07 Javascript
在vue中解决提示警告 for循环报错的方法
2018/09/28 Javascript
vue实现点击隐藏与显示实例分享
2019/02/13 Javascript
vue组件之间通信方式实例总结【8种方式】
2019/02/22 Javascript
纯JS实现五子棋游戏
2020/05/28 Javascript
nuxt 路由、过渡特效、中间件的实现代码
2020/11/06 Javascript
python自带的http模块详解
2016/11/06 Python
python3.x实现发送邮件功能
2018/05/22 Python
python中下标和切片的使用方法解析
2019/08/27 Python
Python Scrapy图片爬取原理及代码实例
2020/06/12 Python
scrapy实践之翻页爬取的实现
2021/01/05 Python
CSS实现进度条和订单进度条的示例
2020/11/05 HTML / CSS
Banggood官网:面向全球客户的综合商城
2017/04/19 全球购物
匡威荷兰官方网站:Converse荷兰
2018/10/24 全球购物
西班牙家用电器和电子产品购物网站:Mi Electro
2019/02/25 全球购物
如何向接受结构参数的函数传入常数值
2016/02/17 面试题
编写函数,将一个3*3矩阵转置
2013/10/09 面试题
户外拓展活动方案
2014/02/11 职场文书
德语专业求职信
2014/03/12 职场文书
考核评语大全
2014/04/29 职场文书
最美护士演讲稿
2014/08/27 职场文书
2014年机关作风建设工作总结
2014/10/23 职场文书
十佳少年事迹材料
2014/12/25 职场文书
起诉书范文
2015/05/20 职场文书
2016年班主任培训心得体会
2016/01/07 职场文书
MongoDB数据库之添删改查
2022/04/26 MongoDB