Select Individual Rows From Multiindex Pandas Dataframe
I am trying to select individual rows from a multiindex dataframe using a list of multiindices. For example. I have got the following dataframe: Col1 A B C 1 1 1 -0.1485
Solution 1:
One option is to use pd.DataFrame.query
:
res = df.query('((A == 1) & (B == 1)) | ((A == 2) & (B == 2))')
print(res)
Col1
A B C
1 1 1 0.981483
2 0.851543
2 2 7 -0.522760
8 -0.332099
For a more generic solution, you can use f-strings (Python 3.6+), which should perform better than str.format
or manual concatenation.
filters = [(1,1), (2,2)]
filterstr = '|'.join(f'(A=={i})&(B=={j})'for i, j in filters)
res = df.query(filterstr)
print(filterstr)
(A==1)&(B==1)|(A==2)&(B==2)
Post a Comment for "Select Individual Rows From Multiindex Pandas Dataframe"