且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从multiindex pandas数据框中选择单个行

更新时间:2023-01-31 16:09:59

一种选择是使用 pd.DataFrame.query

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

对于更通用的解决方案,您可以使用f字符串(Python 3.6及更高版本),其性能应优于 str.format 或手动串联。

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)