Pandas: Choosing with MultiIndex

Given 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 AB 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 df lines with corresponding True values ​​in vals ?

If I reset_index on both frames, I can now combine / merge them and cut them, but I want to, but how to do this using indexes (multi)?

+4
source share
1 answer

boolean indexing is completely ...

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

Please note that you can use xs for multiindex.

 In [66]: df.xs(1) Out[66]: C B 1 10 2 15 
+7
source

Source: https://habr.com/ru/post/1445673/


All Articles