Skip to content

Commit

Permalink
Merge pull request #3124 from jreback/GH2817
Browse files Browse the repository at this point in the history
BUG: GH2817 raise the correct KeyError that the multi-index is not sorted
  • Loading branch information
jreback committed Mar 22, 2013
2 parents b9bb1b5 + 1b2337b commit 3ae98f5
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pandas/core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,9 @@ def values(self):
def is_monotonic(self):
return self._engine.is_monotonic

def is_lexsorted_for_tuple(self, tup):
return True

@cache_readonly
def is_unique(self):
return self._engine.is_unique
Expand Down Expand Up @@ -1692,6 +1695,12 @@ def is_lexsorted(self):
"""
return self.lexsort_depth == self.nlevels

def is_lexsorted_for_tuple(self, tup):
"""
Return True if we are correctly lexsorted given the passed tuple
"""
return len(tup) <= self.lexsort_depth

@cache_readonly
def lexsort_depth(self):
if self.sortorder is not None:
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,10 @@ def _getitem_lowerdim(self, tup):
except Exception, e1:
if isinstance(tup[0], (slice, Index)):
raise IndexingError

# raise the error if we are not sorted
if not ax0.is_lexsorted_for_tuple(tup):
raise e1
try:
loc = ax0.get_loc(tup[0])
except KeyError:
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,23 @@ def test_loc_multiindex(self):
xp = mi_int.ix[4]
assert_frame_equal(rs,xp)

def test_ix_general(self):

# ix general issues

# GH 2817
data={'amount': {0: 700, 1: 600, 2: 222, 3: 333, 4: 444},
'col': {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0},
'year': {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}}
df = DataFrame(data).set_index(keys=['col','year'])

# this should raise correct error
self.assertRaises(KeyError, df.ix.__getitem__, tuple([4.0,2012]))

# this is ok
df.sortlevel(inplace=True)
df.ix[(4.0,2012)]

if __name__ == '__main__':
import nose
nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'],
Expand Down

0 comments on commit 3ae98f5

Please sign in to comment.