Skip to content

Commit e6edc29

Browse files
committed
ENH: Introduce UnsortedIndexError GH11897
1 parent 2f43ac4 commit e6edc29

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

doc/source/whatsnew/v0.20.0.txt

+3
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ Other enhancements
4141

4242
- ``pd.read_excel`` now preserves sheet order when using ``sheetname=None`` (:issue:`9930`)
4343

44+
- New ``UnsortedIndexError`` (subclass of ``KeyError``) thrown when indexing into an
45+
unsorted index (:issue:'11897`)
46+
4447

4548
.. _whatsnew_0200.api_breaking:
4649

pandas/indexes/multi.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@
4444
_index_shared_docs)
4545
import pandas.indexes.base as ibase
4646

47+
class UnsortedIndexError(KeyError):
48+
pass
4749

4850
class MultiIndex(Index):
4951
"""
@@ -1936,7 +1938,8 @@ def get_locs(self, tup):
19361938

19371939
# must be lexsorted to at least as many levels
19381940
if not self.is_lexsorted_for_tuple(tup):
1939-
raise KeyError('MultiIndex Slicing requires the index to be fully '
1941+
raise UnsortedIndexError(
1942+
'MultiIndex Slicing requires the index to be fully '
19401943
'lexsorted tuple len ({0}), lexsort depth '
19411944
'({1})'.format(len(tup), self.lexsort_depth))
19421945

pandas/tests/indexes/test_multi.py

+17
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
CategoricalIndex, compat)
1111
from pandas.core.common import PerformanceWarning
1212
from pandas.indexes.base import InvalidIndexError
13+
from pandas.indexes.multi import UnsortedIndexError
1314
from pandas.compat import range, lrange, u, PY3, long, lzip
1415

1516
import numpy as np
@@ -2535,3 +2536,19 @@ def test_dropna(self):
25352536
msg = "invalid how option: xxx"
25362537
with tm.assertRaisesRegexp(ValueError, msg):
25372538
idx.dropna(how='xxx')
2539+
2540+
def test_unsortedindex(self):
2541+
#GH 11897
2542+
mi = pd.MultiIndex.from_tuples([('z','a'),('x','a'),('y','b'),
2543+
('x','b'),('y','a'),('z','b')],
2544+
names=['one','two'])
2545+
df = pd.DataFrame([[i,10*i] for i in lrange(6)], index=mi,
2546+
columns=['one','two'])
2547+
2548+
with assertRaises(UnsortedIndexError):
2549+
df.loc(axis=0)['z',:]
2550+
df.sort_index(inplace=True)
2551+
self.assertEqual(len(df.loc(axis=0)['z',:]), 2)
2552+
2553+
with assertRaises(KeyError):
2554+
df.loc(axis=0)['q',:]

0 commit comments

Comments
 (0)