在pandas上使用整数索引容易产生歧义,因为它和在列表、元组内构建数据结构进行索引有一点不同。
1.整数索引
如下代码
ser = pd.Series(np.arange(3.))
ser[-1]
返回的结果为:
Traceback (most recent call last):
File "G:\soft\anaconda\install\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-22-3cbe0b873a9e>", line 1, in <module>
ser[-1]
File "G:\soft\anaconda\install\lib\site-packages\pandas\core\series.py", line 583, in __getitem__
result = self.index.get_value(self, key)
File "G:\soft\anaconda\install\lib\site-packages\pandas\indexes\base.py", line 1980, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas\index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas\index.c:3332)
File "pandas\index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas\index.c:3035)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
File "pandas\hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6610)
File "pandas\hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6554)
KeyError: -1
上述的索引引起一些错误,是因为整数索引包含了0,1,2,但是用户使用的索引不一定相同,此时会产生歧义
2.非整数索引
对于非整数索引,一般就不会产生歧义,如下文代码
ser2 = pd.Series(np.arange(3.), index=['a','b','c'])
ser2[-1]
返回结果为:
Out[23]: 2.0
3.处理整数索引数据
为保持一致性,如果有包含整数的轴索引,数据选择时最好使用标签索引。若需要精确处理,可使用loc(用于标签)或者iloc(用于整数)进行处理
loc用于轴标签,iloc用于整数标签
进行运行分析如下
ser[:1]
Out[24]:
0 0.0
dtype: float64
ser.loc[:1]
Out[25]:
0 0.0
1 1.0
dtype: float64
ser.iloc[:1]
Out[26]:
0 0.0
dtype: float64