在用pandas进行DataFrame的处理时,经常需要对某行或某列进行索引,在不同的书中,会用到不同的索引方法。
其中,最常见的就是loc,iloc,ix三种方法。
①loc——通过行标签进行索引
②iloc——通过行号进行索引
③ix——结合前两种的混合索引
举例说明:
import pandas as pd df = pd.DataFrame({'a':[0,1,2],'b':[3,4,5],'c':[6,7,8]},index=['X','Y','Z']
print(df)
a b c X 0 3 6 Y 1 4 7 Z 2 5 8
①loc
索引行:
df.loc['X':'Y'] #正常输出 能取到Y行 a b c X 0 3 6 Y 1 4 7
-
df.loc[0:1] #报错
-
TypeError: cannot do slice indexing on
<class 'pandas.core.indexes.base.Index'> with these indexers [0] of
<class 'int'>
索引列:
df.loc[:,'b':'c'] #正常输出,能取到c列 b c X 3 6 Y 4 7 Z 5 8
-
df.loc[:,1:2] #报错
-
TypeError: cannot do slice indexing on
<class 'pandas.core.indexes.base.Index'> with these indexers [1] of
<class 'int'>
②iloc
索引行:
df.iloc[0:1] #正常输出,取不到第1行 a b c X 0 3 6
-
df.iloc['X':'Y'] #报错
-
TypeError: cannot do slice indexing on
<class 'pandas.core.indexes.base.Index'> with these indexers [X] of
<class 'str'>
索引列:
df.iloc[:,1:2] #正常输出,取不到第2列 b X 3 Y 4 Z 5
-
df.iloc[:,'b':'c'] #报错
-
TypeError: cannot do slice indexing on
<class 'pandas.core.indexes.base.Index'> with these indexers [b] of
<class 'str'>
③ix
索引行:
df.ix['X':'Z'] #正常输出,能取到Z行 a b c X 0 3 6 Y 1 4 7 Z 2 5 8
df.ix[0:2] #正常输出,取不到第2行 a b c X 0 3 6 Y 1 4 7
索引列:
df.ix[:,'a':'c'] #正常输出,能取到第c列 a b c X 0 3 6 Y 1 4 7 Z 2 5 8
df.ix[:,0:2] #正常输出,取不到第2列 a b X 0 3 Y 1 4 Z 2 5