From 8fbd2f3f643d0ebdf27376a9dba5d4bcaee11ee6 Mon Sep 17 00:00:00 2001 From: Andreas Berneryd Date: Sat, 19 Aug 2017 16:54:38 +0200 Subject: [PATCH] BUG: Fix strange behaviour of Series.iloc on MultiIndex Series (#17148) --- doc/source/whatsnew/v0.21.0.txt | 1 + pandas/core/indexing.py | 3 ++- pandas/tests/indexing/test_iloc.py | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 85685ed7b430d9..4be33a6ce4b697 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -329,6 +329,7 @@ Indexing - Fixes ``DataFrame.loc`` for setting with alignment and tz-aware ``DatetimeIndex`` (:issue:`16889`) - Avoids ``IndexError`` when passing an Index or Series to ``.iloc`` with older numpy (:issue:`17193`) - Allow unicode empty strings as placeholders in multilevel columns in Python 2 (:issue:`17099`) +- Bug ``Series`` with ``MultiIndex`` gives surprising ``.iloc`` results when an integer indexer is used (:issue: `17148`) I/O ^^^ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 109183827de4e8..eda438737ec26a 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -146,7 +146,8 @@ def _get_setitem_indexer(self, key): return self._convert_tuple(key, is_setter=True) axis = self.obj._get_axis(0) - if isinstance(axis, MultiIndex): + + if isinstance(axis, MultiIndex) and not isinstance(key, int): try: return axis.get_loc(key) except Exception: diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 31fee303a41e20..47360ca14401e0 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -269,6 +269,14 @@ def test_iloc_setitem(self): expected = Series([0, 1, 0], index=[4, 5, 6]) tm.assert_series_equal(s, expected) + df = pd.DataFrame(data=[[1, 2, 5], [1, 3, 6]], columns=['i', 'j', 'k']) + df.set_index(['i', 'j'], inplace=True) + s = df.k.copy() + s.iloc[1] = 1 + df.values[1][0] = 1 + expected = df.k + tm.assert_series_equal(s, expected) + def test_iloc_setitem_list(self): # setitem with an iloc list