1

I have a DataFrame with index (a, b)

df = pd.DataFrame({'a' : [1, 2, 3, 1], 'b' : [11, 11, 11, -7], 'val' : [10, 19, 24, 12]})
df.set_index(['a', 'b'], inplace=True)
a | b  | val
1 | 11 | 10
2 | 11 | 19
3 | 11 | 24
1 | -7 | 12

I'd like to pick from it only the rows with b == 11.

I've tried

df[df.index[1] == 11]

KeyError: False

It failed. Could you help?

4
  • 1
    You can use xs. Please check: df.xs(11, level=1) Commented Jul 4, 2022 at 17:05
  • That's the solution) @shubham-sharma, could you post it so I can accept it? Commented Jul 4, 2022 at 17:38
  • @Gooselt I think this question might be a duplicate so I'll pass on adding an answer but anyways thanks! Commented Jul 4, 2022 at 17:46
  • There is an alternative with loc to keep the second level. Commented Jul 4, 2022 at 18:15

1 Answer 1

2

There are 2 options to pick the rows with b==11.

  1. As suggested by @ShubhamSharma, you can use xs but you lost the level b:
>>> df.xs(11, level=1)
   val
a     
1   10
2   19
3   24
  1. You can also use loc and pd.IndexSlice if you want to keep the level:
>>> df.loc[pd.IndexSlice[:, 11], :]
      val
a b      
1 11   10
2 11   19
3 11   24
Sign up to request clarification or add additional context in comments.

1 Comment

The IndexSlice tip is to me the most expressive option. Most familiar in its use too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.