从multiindex pandas数据框中选择单个行 [英] select individual rows from multiindex pandas dataframe

查看:109
本文介绍了从multiindex pandas数据框中选择单个行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用多索引列表从多索引数据框中选择单个行。

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.148593
    2  2.043589
  2 3 -1.696572
    4 -0.249049
2 1 5  2.012294
    6 -1.756410
  2 7  0.476035
    8 -0.531612

我想选择(A,B)= [(1,1),(2 ,2)]

I would like to select all 'C' with (A,B) = [(1,1), (2,2)]

           Col1
A B C
1 1 1 -0.148593
    2  2.043589
2 2 7  0.476035
    8 -0.531612

我对此有缺陷的代码是

import pandas as pd
import numpy as np

arrays = [np.array([1, 1, 1, 1, 2, 2, 2, 2]), np.array([1, 1, 2, 2, 1, 1, 2, 2]), np.array([1, 2, 3, 4, 5, 6, 7, 8])]
df = pd.DataFrame(np.random.randn(8), index=arrays, columns=['Col1'])
df.rename_axis(['A','B','C'], inplace=True)
print(df)

idx_lst = [(1,1), (2,2)]
test = df.loc(axis=0)[idx_lst]
print(test)


推荐答案

一种选择是使用 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)

这篇关于从multiindex pandas数据框中选择单个行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆