Skip to content

BUG: raise KeyError if missing value in py3 on multi-index (GH5725), revisted #5737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 19, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pandas/core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -2306,8 +2306,11 @@ def _try_mi(k):
compat.PY3 and isinstance(key, compat.string_types)):
try:
return _try_mi(key)
except (KeyError):
raise
except:
pass

try:
return _try_mi(Timestamp(key))
except:
Expand Down
23 changes: 22 additions & 1 deletion pandas/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,15 +844,36 @@ def test_getitem_multiindex(self):
# GH 5725
# the 'A' happens to be a valid Timestamp so the doesn't raise the appropriate
# error, only in PY3 of course!
index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
index = MultiIndex(levels=[['D', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
names=['tag', 'day'])
arr = np.random.randn(len(index),1)
df = DataFrame(arr,index=index,columns=['val'])
result = df.val['D']
expected = Series(arr.ravel()[0:3],name='val',index=Index([26,37,57],name='day'))
assert_series_equal(result,expected)

def f():
df.val['A']
self.assertRaises(KeyError, f)

def f():
df.val['X']
self.assertRaises(KeyError, f)

# A is treated as a special Timestamp
index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]],
labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]],
names=['tag', 'day'])
df = DataFrame(arr,index=index,columns=['val'])
result = df.val['A']
expected = Series(arr.ravel()[0:3],name='val',index=Index([26,37,57],name='day'))
assert_series_equal(result,expected)

def f():
df.val['X']
self.assertRaises(KeyError, f)

def test_setitem_dtype_upcast(self):

# GH3216
Expand Down