[转载]pandas切片索引中loc、iloc、ix的区别

在用pandas进行DataFrame的处理时,经常需要对某行或某列进行索引,在不同的书中,会用到不同的索引方法。

其中,最常见的就是loc,iloc,ix三种方法。

①loc——通过行标签进行索引

②iloc——通过行号进行索引

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

举例说明:


   
   
  1. import pandas as pd
  2. df = pd.DataFrame({'a':[0,1,2],'b':[3,4,5],'c':[6,7,8]},index=['X','Y','Z']
print(df)
   
   

   
   
  1. a b c
  2. X 0 3 6
  3. Y 1 4 7
  4. Z 2 5 8

①loc

索引行:


   
   
  1. df.loc['X':'Y'] #正常输出 能取到Y行
  2. a b c
  3. X 0 3 6
  4. Y 1 4 7

   
   
  1. df.loc[0:1] #报错
  2. TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>

索引列:


   
   
  1. df.loc[:,'b':'c'] #正常输出,能取到c列
  2.     b    c
  3. X 3 6
  4. Y 4 7
  5. Z 5 8

   
   
  1. df.loc[:,1:2] #报错
  2. TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1] of <class 'int'>

②iloc

索引行:


   
   
  1. df.iloc[0:1] #正常输出,取不到第1行
  2.     a    b    c
  3. X 0 3 6

   
   
  1. df.iloc['X':'Y'] #报错
  2. TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [X] of <class 'str'>

索引列:


   
   
  1. df.iloc[:,1:2] #正常输出,取不到第2列
  2.     b
  3. X 3
  4. Y 4
  5. Z 5

   
   
  1. df.iloc[:,'b':'c'] #报错
  2. TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [b] of <class 'str'>

③ix

索引行:


   
   
  1. df.ix['X':'Z'] #正常输出,能取到Z行
  2.     a    b    c
  3. X 0 3 6
  4. Y 1 4 7
  5. Z 2 5 8

   
   
  1. df.ix[0:2] #正常输出,取不到第2行
  2.     a    b    c
  3. X 0 3 6
  4. Y 1 4 7

索引列:


   
   
  1. df.ix[:,'a':'c'] #正常输出,能取到第c列
  2. a b c
  3. X 0 3 6
  4. Y 1 4 7
  5. Z 2 5 8

   
   
  1. df.ix[:,0:2] #正常输出,取不到第2列
  2.     a    b
  3. X 0 3
  4. Y 1 4
  5. Z 2 5
发布了4 篇原创文章 · 获赞 0 · 访问量 746

猜你喜欢

转载自blog.csdn.net/u013310037/article/details/103655796