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'

3
  • 1
    Seems this answer has all you will need. stackoverflow.com/questions/53927460/… Commented Aug 10, 2021 at 14:54
  • df.loc[:, df.columns.get_level_values(1).isin(["c","e"])]? Commented Aug 10, 2021 at 15:00
  • thanks guys, sorry I am new to stack overflow :) Commented Aug 11, 2021 at 15:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.