The isin()
method applied to a Pandas index returns whether each index value is found in the passed set of values, but is there a possibility to test only a set of indexe values ?
In the multiIndex below I would like to test if an index with level name s1
and level value E
and level name d1
and level value future
exists. Problem is that I test index values that may not exist so selection method like xs
or loc
don’ work.
JavaScript
x
9
1
df_routes.index
2
MultiIndex([('E', 'future', 'B', 'future'),
3
('E', 'future', 'B5', 'future'),
4
('E', 'future', 'B', 'spot'),
5
('B', 'future', 'B', 'future'),
6
('B', 'future', 'B5', 'future'),
7
('B', 'future', 'B', 'spot')],
8
names=['s1', 'd1', 's2', 'd2'])
9
My problem is that isin()
returns False when using any
as index values :
JavaScript
1
4
1
df_routes.index.isin([('E', 'future', any, any)])
2
3
array([False, False, False, False, False, False])
4
The desired result would be :
JavaScript
1
2
1
array([True, True, True, False, False, False])
2
There is a similar question here but the answer only works for index not multiindex.
How can i do that ?
Advertisement
Answer
If you wanna filter the dataframe using multi-index, just use .loc
JavaScript
1
2
1
df.loc[('E', 'future')]
2
Sample DataFrame
JavaScript
1
9
1
0
2
s1 d1 s2 d2
3
E future B future 1
4
B5 future 2
5
B spot 3
6
B future B future 4
7
B5 future 5
8
B spot 6
9
Ouput
JavaScript
1
6
1
0
2
s2 d2
3
B future 1
4
B5 future 2
5
B spot 3
6
To create a boolean array
JavaScript
1
2
1
(df.index.get_level_values(0) == 'E') & (df.index.get_level_values(1) == 'future')
2