From 2edd3ba2ec80dc0ed3d8e809c5fbe6727dd17f42 Mon Sep 17 00:00:00 2001 From: jreback Date: Fri, 4 Jul 2014 11:38:39 -0400 Subject: [PATCH] BUG: Bug in multi-index slice setting, related GH3738 --- pandas/core/index.py | 9 +++++++++ pandas/tests/test_indexing.py | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/pandas/core/index.py b/pandas/core/index.py index 525d17c7612a7..51ddacd00af08 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -523,6 +523,10 @@ def _convert_slice_indexer_getitem(self, key, is_index_slice=False): def _convert_slice_indexer(self, key, typ=None): """ convert a slice indexer. disallow floats in the start/stop/step """ + # if we are not a slice, then we are done + if not isinstance(key, slice): + return key + # validate iloc if typ == 'iloc': @@ -2008,6 +2012,11 @@ def _convert_scalar_indexer(self, key, typ=None): def _convert_slice_indexer(self, key, typ=None): """ convert a slice indexer, by definition these are labels unless we are iloc """ + + # if we are not a slice, then we are done + if not isinstance(key, slice): + return key + if typ == 'iloc': return super(Float64Index, self)._convert_slice_indexer(key, typ=typ) diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py index 1a4da63a135a2..0e962800fef08 100644 --- a/pandas/tests/test_indexing.py +++ b/pandas/tests/test_indexing.py @@ -1883,6 +1883,29 @@ def f(): df.loc['bar'] *= 2 self.assertRaises(TypeError, f) + # from SO + #http://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation + df_orig = DataFrame.from_dict({'price': { + ('DE', 'Coal', 'Stock'): 2, + ('DE', 'Gas', 'Stock'): 4, + ('DE', 'Elec', 'Demand'): 1, + ('FR', 'Gas', 'Stock'): 5, + ('FR', 'Solar', 'SupIm'): 0, + ('FR', 'Wind', 'SupIm'): 0}}) + df_orig.index = MultiIndex.from_tuples(df_orig.index, names=['Sit', 'Com', 'Type']) + + expected = df_orig.copy() + expected.iloc[[0,2,3]] *= 2 + + idx = pd.IndexSlice + df = df_orig.copy() + df.loc[idx[:,:,'Stock'],:] *= 2 + assert_frame_equal(df, expected) + + df = df_orig.copy() + df.loc[idx[:,:,'Stock'],'price'] *= 2 + assert_frame_equal(df, expected) + def test_getitem_multiindex(self): # GH 5725