详谈Pandas中iloc和loc以及ix的区别
技术  /  管理员 发布于 7年前   168
Pandas库中有iloc和loc以及ix可以用来索引数据,抽取数据。但是方法一多也容易造成混淆。下面将一一来结合代码说清其中的区别。
1. iloc和loc的区别:
iloc主要使用数字来索引数据,而不能使用字符型的标签来索引数据。而loc则刚好相反,只能使用字符型标签来索引数据,不能使用数字来索引数据,不过有特殊情况,当数据框dataframe的行标签或者列标签为数字,loc就可以来其来索引。
好,先上代码,先上行标签和列标签都为数字的情况。
import pandas as pdimport numpy as npa = np.arange(12).reshape(3,4)print a>>>[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]]df = pd.DataFrame(a)print df>>> 0 1 2 30 0 1 2 31 4 5 6 72 8 9 10 11print df.loc[0]>>>0 01 12 23 3Name: 0, dtype: int32print df.iloc[0]0 01 12 23 3Name: 0, dtype: int32print df.loc[:,[0,3]] 0 30 0 31 4 72 8 11print df.iloc[:,[0,3]] 0 30 0 31 4 72 8 11
接下来是把行标签[0, 1, 2]改成['a', 'b', 'c'],则成这样了。
df.index = ['a','b','c'] print df >>> 0 1 2 3 a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 print df.loc[0] # TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <type 'int'> print df.iloc[0] >>> 0 0 1 1 2 2 3 3 Name: a, dtype: int32 print df.iloc['a'] # TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [a] of <type 'str'> print df.loc['a'] # 正确 >>> 0 0 1 1 2 2 3 3 Name: a, dtype: int32
同样地,把列标签[0, 1, 2, 3]改成['A', 'B, 'C', 'D'],则成这样了。
df.columns = ['A','B','C','D']print df>>> A B C Da 0 1 2 3b 4 5 6 7c 8 9 10 11print df.loc[:,'A']>>>a 0b 4c 8Name: A, dtype: int32print df.iloc[:,'A'] # ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
2.ix是一种混合索引,字符型标签和整型数据索引都可以。
print df.ix[0]>>>A 0B 1C 2D 3Name: a, dtype: int32print df.ix['a']>>>A 0B 1C 2D 3Name: a, dtype: int32print df.ix[:,0]>>>a 0b 4c 8Name: A, dtype: int32print df.ix[:,'A']>>>a 0b 4c 8Name: A, dtype: int32
以上这篇详谈Pandas中iloc和loc以及ix的区别就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号