为什么我在一种情况下会得到 KeyError,而在另一种情况下却不会?见下文。
>>> import pandas as pd
>>> s1 = pd.Series([10, 20, 30, 40], index=list('abcd'))
>>> s2 = pd.Series([10, 20, 30, 40], index=list('acbd'))
>>> s1.loc['a':'z']
a 10
b 20
c 30
d 40
dtype: int64
>>> s2.loc['a':'z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/lib/python2.7/site-packages/pandas/core/series.py", line 559, in __getitem__
return self._get_with(key)
File "/path/lib/python2.7/site-packages/pandas/core/series.py", line 564, in _get_with
indexer = self.index._convert_slice_indexer(key, kind='getitem')
File "/path/lib/python2.7/site-packages/pandas/core/index.py", line 871, in _convert_slice_indexer
key, is_index_slice=is_index_slice)
File "/path/lib/python2.7/site-packages/pandas/core/index.py", line 806, in _convert_slice_indexer_getitem
return self._convert_slice_indexer(key)
File "/path/lib/python2.7/site-packages/pandas/core/index.py", line 893, in _convert_slice_indexer
indexer = self.slice_indexer(start, stop, step)
File "/path/lib/python2.7/site-packages/pandas/core/index.py", line 2346, in slice_indexer
start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind)
File "/path/lib/python2.7/site-packages/pandas/core/index.py", line 2496, in slice_locs
end_slice = self.get_slice_bound(end, 'right', kind)
File "/path/lib/python2.7/site-packages/pandas/core/index.py", line 2438, in get_slice_bound
raise err
KeyError: 'z'
更新: 其中一个答案说这可能是因为 s1.index.is_monotonic 是真的。但是这里有一个例子,is_monotonic 是False,但是没有KeyError。
>>> s3 = pd.Series([10, 20, 30, 40], index=list('dcba'))
>>> s3['z':'a']
d 10
c 20
b 30
a 40
dtype: int64
>>> s3.index.is_monotonic
False
Python v2.7.5,pandas v0.16.1
请您参考如下方法:
我认为这归结为 t 的索引不是单调的,即它没有排序。排序/单调索引允许一些未排序索引不可能的行为。
s.index.is_monotonic
Out[15]: True
t.index.is_monotonic
Out[16]: False
docs on multi-indexing 中简要提到了这一点,虽然显然这并不完全适用于您的情况,但我不确定去哪里可以很好地了解切片如何对排序/未排序的索引起作用。
