在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