详解Pandas中iloc、loc与ix索引方法的区别及用法
本文详细解析Pandas库中iloc、loc及ix三种索引方法的区别。iloc仅支持整数位置索引,loc仅支持标签索引(含数字标签特殊情况),而ix为混合索引。通过代码示例展示不同标签类型下的行为差异,帮助开发者避免索引混淆,正确抽取数据。
在Pandas库中,iloc、loc以及ix均可用于数据的索引与抽取。然而,由于方法众多且功能相近,初学者容易混淆。下文将结合具体代码实例,逐一阐明它们之间的核心区别。
1. iloc与loc的核心区别
iloc方法主要依赖整数位置对数据进行索引,不支持使用字符型标签进行索引。相反,loc方法仅接受字符型标签作为索引依据,不能直接使用整数位置进行索引。但存在一种特殊情况:当DataFrame的行标签或列标签本身为数字时,loc方法也可以利用这些数字标签进行索引。
首先,通过代码演示当行标签和列标签均为数字时的情形。
import pandas as pd import numpy as np a = 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 3 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 print df.loc[0] >>> 0 0 1 1 2 2 3 3 Name: 0, dtype: int32 print df.iloc[0] 0 0 1 1 2 2 3 3 Name: 0, dtype: int32 print df.loc[:,[0,3]] 0 3 0 0 3 1 4 7 2 8 11 print df.iloc[:,[0,3]] 0 3 0 0 3 1 4 7 2 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 D a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 print df.loc[:,'A'] >>> a 0 b 4 c 8 Name: A, dtype: int32 print 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 0 B 1 C 2 D 3 Name: a, dtype: int32 print df.ix['a'] >>> A 0 B 1 C 2 D 3 Name: a, dtype: int32 print df.ix[:,0] >>> a 0 b 4 c 8 Name: A, dtype: int32 print df.ix[:,'A'] >>> a 0 b 4 c 8 Name: A, dtype: int32
以上关于Pandas中iloc、loc以及ix区别的详细解析即为全部内容,希望能对读者有所帮助。欢迎参考,并期待大家继续支持本站。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













