pandas ix &iloc &loc的区别
一开始自学Python的numpy、pandas时候,索引和切片把我都给弄晕了,特别是numpy的切片索引、布尔索引和花式索引,简直就是大乱斗。但是最近由于版本的问题,从之前的Python2.7改用Python3.6了,在3.6中提供了loc和iloc两种索引方法,把ix这个方法给划分开来了,所以很有必要做个总结和对比。
- loc——通过行标签索引行数据
- iloc——通过行号索引行数据
- ix——通过行标签或者行号索引行数据(基于loc和iloc的混合)
同理,索引列数据也是如此!
举例说明:
1、分别使用loc、iloc、ix索引第一行的数据:
(1)loc
importpandasaspd data=[[1,2,3],[4,5,6]] index=['a','b']#行号 columns=['c','d','e']#列号 df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框 #printdf.loc['a'] ''' c1 d2 e3 ''' printdf.loc[0] #这个就会出现错误 ''' TypeError:cannotdolabelindexingonwiththeseindexers[1]of '''
(2)iloc
importpandasaspd data=[[1,2,3],[4,5,6]] index=['a','b']#行号 columns=['c','d','e']#列号 df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框 printdf.iloc[0] ''' c1 d2 e3 ''' printdf.iloc['a'] ''' TypeError:cannotdopositionalindexingonwiththeseindexers[a]of '''
(3)ix
importpandasaspd data=[[1,2,3],[4,5,6]] index=['a','b']#行号 columns=['c','d','e']#列号 df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框 printdf.ix[0] ''' c1 d2 e3 ''' printdf.ix['a'] ''' c1 d2 e3 '''
2、分别使用loc、iloc、ix索引第一列的数据:
importpandasaspd data=[[1,2,3],[4,5,6]] index=['a','b']#行号 columns=['c','d','e']#列号 df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框 printdf.loc[:,['c']] printdf.iloc[:,[0]] printdf.ix[:,['c']] printdf.ix[:,[0]] #结果都为 ''' c a1 b4 '''
3、分别使用loc、iloc、ix索引多行的数据:
importpandasaspd data=[[1,2,3],[4,5,6]] index=['a','b']#行号 columns=['c','d','e']#列号 df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框 printdf.loc['a':'b'] printdf.iloc[0:1] printdf.ix['a':'b'] printdf.ix[0:1] #结果都为 ''' cde a123 b456 '''
4、分别使用loc、iloc、ix索引多列的数据:
importpandasaspd data=[[1,2,3],[4,5,6]] index=['a','b']#行号 columns=['c','d','e']#列号 df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框 printdf.loc[:,'c':'d'] printdf.iloc[:,0:2] printdf.ix[:,'c':'d'] printdf.ix[:,0:2] #结果都为 ''' cd a12 b45 '''
5、loc、iloc、ix使用切片的区别
loc、iloc、ix对于切片的索引数据就两种情况,按照标签切片索引和按照位置编号切片索引
In[20]:df.loc['ind0':'ind3'] Out[20]: col0col1col2col3col4 ind001234 ind156789 ind21011121314 ind31516171819 In[21]:df.iloc[0:3] Out[21]: col0col1col2col3col4 ind001234 ind156789 ind21011121314
区别不在于用哪种方法,而是通过标签索引将会将切片末端包含进去,通过位置编号索引不会讲切片末端包含进去。同样的都是第一行到第四行,通过loc就会把1,2,3,4行都提取出来,通过iloc就只能把1,2,3行提取出来。ix方法也是一样,知识方法不同而已。
In[23]:df.ix['ind0':'ind3'] Out[23]: col0col1col2col3col4 ind001234 ind156789 ind21011121314 ind31516171819 In[24]:df.ix[0:3] Out[24]: col0col1col2col3col4 ind001234 ind156789 ind21011121314
对于列的切片跟行的一样。
这里讨论了基本的索引和切片,如果有用词不当的地方请提出来,我将积极改正,或者有其他有关花式索引、布尔索引的问题也可以大家一起讨论讨论!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。