如何基于熊猫中的列条件选择多行作为组

时间:2019-07-25 23:19:03

标签: python python-3.x pandas

如何根据列条件选择不同匹配组中的所有行

数据:

**A B   C   D** 

101 1   1   FALSE

101 1   2   FALSE

101 1   3   FALSE

101 2   1   FALSE

101 2   2   FALSE

101 2   3   FALSE

101 2   4   TRUE

102 1   1   FALSE

102 1   2   FALSE

102 1   3   FALSE

102 2   1   FALSE

102 2   2   FALSE

102 2   3   TRUE

预期输出:

**A B   C   D**

101 2   1   FALSE

101 2   2   FALSE

101 2   3   FALSE

101 2   4   TRUE

102 2   1   FALSE

102 2   2   FALSE

102 2   3   TRUE

我需要B =(D = True时为B)的所有行

df.loc[df.groupby(["A"])[df_rvtlt['D'] == True]]

2 个答案:

答案 0 :(得分:1)

IIUC,使用groupby + filter

df.groupby(['A', 'B']).filter(lambda s: s['D'].any())

    A   B   C   D
3   101 2   1   False
4   101 2   2   False
5   101 2   3   False
6   101 2   4   True
10  102 2   1   False
11  102 2   2   False
12  102 2   3   True

答案 1 :(得分:1)

这是从transform

的一种方式
df[df.groupby(['A','B']).D.transform('mean')>0]
Out[256]: 
      A  B  C      D
3   101  2  1  False
4   101  2  2  False
5   101  2  3  False
6   101  2  4   True
10  102  2  1  False
11  102  2  2  False
12  102  2  3   True

使用any

df[df.groupby(['A','B']).D.transform('any')]