Home > database >  Using loc in pandas without discarding the outer levels
Using loc in pandas without discarding the outer levels

Time:02-17

I have a dataframe like

df = pd.DataFrame({
    'level0': [0,1,2],
    'level1': ['a', 'b', 'b'],
    'level2':['x', 'x', 'x'],
    'data': [0.12, 0.34, 0.45]}
).set_index(['level0', 'level1', 'level2'])
level0 level1 level 2 data
0 a x 0.12
1 b x 0.34
2 b x 0.56

If level0, level1, and level2 are the index levels, I want to access the data at (2, b) but keep the first two levels of labels. If I do df.loc[(2, 'b')] the output is

level2 data
x 0.56

but my desired output is

level0 level1 level 2 data
2 b x 0.56

How do I keep the levels 0 and 1 while using loc? I could add these levels back afterwards, but this is slightly annoying, and I'm doing this frequently enough to wonder if there's a one step solution.

CodePudding user response:

You can use MultiIndex.get_locs:

>>> df.loc[df.index.get_locs((2, 'b'))]

                      data
level0 level1 level2      
2      b      x       0.45
  • Related