如何根据表中的列条件选择多行作为一个组

2024-10-03 02:46:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

数据:

**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]]

Tags: 数据falsetruedf条件locgroupbyrvtlt
2条回答

这里有一条从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')]

IIUC,使用^{}+^{}

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

相关问题 更多 >