4

Considering the following DataFrames

In [136]:
df = pd.DataFrame({'A':[1,1,2,2],'B':[1,2,1,2],'C':np.arange(10,30,5)}).set_index(['A','B'])
df
Out[136]:
      C
A B    
1 1  10
  2  15
2 1  20
  2  25

In [130]:
vals = pd.DataFrame({'A':[1,2],'values':[True,False]}).set_index('A')
vals
Out[130]:
  values
A       
1   True
2  False

How can I select only the rows of df with corresponding True values in vals?

If I reset_index on both frames I can now merge/join them and slice however I want, but how can I do it using the (multi)indexes?

foglerit
  • 7,792
  • 8
  • 44
  • 64
  • can you clarify what you mean by "select only the rows of `df` with corresponding `True` values in `vals`"? I don't quite get what you want to achieve. – Calvin Cheng Nov 13 '12 at 09:33

1 Answers1

7

boolean indexing all the way...

In [65]: df[pd.Series(df.index.get_level_values('A')).isin(vals[vals['values']].index)]
Out[65]: 
      C
A B    
1 1  10
  2  15

Note that you can use xs on a multiindex.

In [66]: df.xs(1)
Out[66]: 
    C
B    
1  10
2  15
Wouter Overmeire
  • 65,766
  • 10
  • 63
  • 43