0

I am wondering if it is possible to select multiple items from one multi-index level?

Say I have a pandas dataframe such as this:

lvl_1      A             B
lvl_2      d      c      f      e
0     -1.406  0.548 -0.635  0.576
1     -0.212 -0.583  1.012 -1.377
2      0.951 -0.349 -0.477 -1.230
3      0.451 -0.168  0.949  0.545
4     -0.362 -0.855  1.676 -2.881
5      1.283  1.027  0.085 -1.282
6      0.583 -1.406  0.327 -0.146
7     -0.518 -0.480  0.139  0.851
8     -0.030 -0.630 -1.534  0.534
9      0.246 -1.558 -1.885 -1.543

I want to select specific columns using lvl_2 of the dataframe

Trying something like df.xs(['c','e'], level='lvl_2', axis=1) leads to an error:

KeyError: 'e'

not_speshal
  • 22,093
  • 2
  • 15
  • 30

1 Answers1

0

You can use pd.IndexSlice with .loc, as follows:

idx = pd.IndexSlice
df.loc[:, idx[:, ['c', 'e']]]

Result:

lvl_1      A      B
lvl_2      c      e
0      0.548  0.576
1     -0.583 -1.377
2     -0.349 -1.230
3     -0.168  0.545
4     -0.855 -2.881
5      1.027 -1.282
6     -1.406 -0.146
7     -0.480  0.851
8     -0.630  0.534
9     -1.558 -1.543
SeaBean
  • 22,547
  • 3
  • 13
  • 25