Skip to content Skip to sidebar Skip to footer

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)

Solution 2:

The following might help:

idx_lst = [(1,1), (2,2)]

df.loc(0)[[ z for z in df.index if (z[0], z[1]) in idx_lst ]]
# Out[941]: #            Col1# A B C          # 1 1 1  0.293952#     2  0.197045# 2 2 7  2.007493#     8  0.937420

Post a Comment for "Select Individual Rows From Multiindex Pandas Dataframe"