foglerit
foglerit

Reputation: 8279

Pandas: Selection with MultiIndex

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?

Upvotes: 4

Views: 2267

Answers (1)

Wouter Overmeire
Wouter Overmeire

Reputation: 69256

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

Upvotes: 7

Related Questions