Pandas中ix,loc, iloc的用法及区别

Pandas在对Series和DataFrame进行行列索引时,有三种常用的方法。其中.ix方法兼顾了.loc和.iloc的用法。为了避免用户在使用这三种方法时产生混淆,从pandas 0.20.0版本开始,官方不推荐使用.ix方法而是使用.iloc 和.loc方法。

.loc()方法:(1)使用行标签和列标签,获取行、列对应的某一个值
(2)选定某一个区域的值
注意:.loc()方法的的取值范围都是闭区间
.iloc()方法:(1)采用索引获取某一个值,且行和列中后区间为开区间
(2)选定某一个区域的值
注意:行索引和列索引的起始值为0

loc——通过行标签索引行数据

loc[‘d’]表示索引的是第’d’行(index 是字符)

import pandas as pd  
data = [[1,2,3],[4,5,6]]  
index = ['d','e']  
columns=['a','b','c']  
df = pd.DataFrame(data=data, index=index, columns=columns)  

df数据样式:

abc
d123
e456
df.loc['d']  
a1
b2
c3

如果想索引列数据,像这样做会报错

print df.loc['a']  

‘’’’’
KeyError: ‘the label [a] is not in the [index]’
‘’’

loc可以获取多行数据

print df.loc['d':]  
abc
d123
e456

loc扩展——索引某行某列

print df.loc['d',['b','c']]  
b2
c3

loc扩展——索引某列

print df.loc[:,['c']]  
c
d3
e6

当然获取某列数据最直接的方式是df.[列标签],但是当列标签未知时可以通过这种方式获取列数据。
注意:dataframe的索引[1:3]是包含1,2,3的,与平时的不同。

iloc——通过行号获取行数据

想要获取哪一行就输入该行数字

df.iloc[1]  
a4
b5
c6

通过行标签索引会报错

print df.iloc['a']  

‘’’’’
TypeError: cannot do label indexing on <class ‘pandas.core.index.Index’> with these indexers [a] of <type ‘str’>
‘’’

同样通过行号可以索引多行

df.iloc[0:]  
abc
d123
e456

iloc索引列数据

df.iloc[:,[1]]  
b
d2
e5

ix——结合前两种的混合索引

通过行号索引

df.ix[1]  
a4
b5
c6

通过行标签索引

df.ix['e']  
a4
b5
c6
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值