Skip to content

Commit 56fc093

Browse files
committed
Merge pull request #7667 from jreback/mi_slicing
BUG: Bug in multi-index slice setting, related GH3738
2 parents 03bbed5 + 2edd3ba commit 56fc093

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

pandas/core/index.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,10 @@ def _convert_slice_indexer_getitem(self, key, is_index_slice=False):
523523
def _convert_slice_indexer(self, key, typ=None):
524524
""" convert a slice indexer. disallow floats in the start/stop/step """
525525

526+
# if we are not a slice, then we are done
527+
if not isinstance(key, slice):
528+
return key
529+
526530
# validate iloc
527531
if typ == 'iloc':
528532

@@ -2008,6 +2012,11 @@ def _convert_scalar_indexer(self, key, typ=None):
20082012
def _convert_slice_indexer(self, key, typ=None):
20092013
""" convert a slice indexer, by definition these are labels
20102014
unless we are iloc """
2015+
2016+
# if we are not a slice, then we are done
2017+
if not isinstance(key, slice):
2018+
return key
2019+
20112020
if typ == 'iloc':
20122021
return super(Float64Index, self)._convert_slice_indexer(key,
20132022
typ=typ)

pandas/tests/test_indexing.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1883,6 +1883,29 @@ def f():
18831883
df.loc['bar'] *= 2
18841884
self.assertRaises(TypeError, f)
18851885

1886+
# from SO
1887+
#http://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation
1888+
df_orig = DataFrame.from_dict({'price': {
1889+
('DE', 'Coal', 'Stock'): 2,
1890+
('DE', 'Gas', 'Stock'): 4,
1891+
('DE', 'Elec', 'Demand'): 1,
1892+
('FR', 'Gas', 'Stock'): 5,
1893+
('FR', 'Solar', 'SupIm'): 0,
1894+
('FR', 'Wind', 'SupIm'): 0}})
1895+
df_orig.index = MultiIndex.from_tuples(df_orig.index, names=['Sit', 'Com', 'Type'])
1896+
1897+
expected = df_orig.copy()
1898+
expected.iloc[[0,2,3]] *= 2
1899+
1900+
idx = pd.IndexSlice
1901+
df = df_orig.copy()
1902+
df.loc[idx[:,:,'Stock'],:] *= 2
1903+
assert_frame_equal(df, expected)
1904+
1905+
df = df_orig.copy()
1906+
df.loc[idx[:,:,'Stock'],'price'] *= 2
1907+
assert_frame_equal(df, expected)
1908+
18861909
def test_getitem_multiindex(self):
18871910

18881911
# GH 5725

0 commit comments

Comments
 (0)