TAGS :Viewed: 8 - Published at: a few seconds ago

[ pandas: KeyError in one case, but not in another similar case ]

Why do I get a KeyError in one case, but not the other? See below.

>>> 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'

Update: One of the answers said that this could be because s1.index.is_monotonic is true. But here is a case where is_monotonic is False, but there is no 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

Answer 1


I think this comes down to the fact that the index for t is not monotonic, i.e. it's not sorted. Sorted/monotonic indexes allow for a few behaviours that are not possible for unsorted ones.

s.index.is_monotonic
Out[15]: True

t.index.is_monotonic
Out[16]: False

This is briefly mentioned in the docs on multi-indexing, although obviously that doesn't quite apply in your case, I'm not sure where to go for a good overview of how slicing works for sorted/unsorted indices.