python - pandas: KeyError in one case, but not in another similar case -
why keyerror in 1 case, not other? see below.
>>> import pandas 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'] 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: 1 of answers said because s1.index.is_monotonic
true. here case is_monotonic
false
, there no keyerror
.
>>> s3 = pd.series([10, 20, 30, 40], index=list('dcba')) >>> s3['z':'a'] d 10 c 20 b 30 40 dtype: int64 >>> s3.index.is_monotonic false
python v2.7.5, pandas v0.16.1
i think comes down fact index t
not monotonic, i.e. it's not sorted. sorted/monotonic indexes allow few behaviours not possible unsorted ones.
s.index.is_monotonic out[15]: true t.index.is_monotonic out[16]: false
this briefly mentioned in docs on multi-indexing, although doesn't quite apply in case, i'm not sure go overview of how slicing works sorted/unsorted indices.
Comments
Post a Comment