在“熊猫”列中将值分组在一起,然后在另一列中过滤值

pym*_*mat 1 pandas python-3.6

熊猫数据框如下所示:

Col1 Col2

A    1
A    1
A    1
B    0
B    0
B    1
B    1
B    1
C    1
C    1
C    1
C    1
Run Code Online (Sandbox Code Playgroud)

我想将所有分组在一起Col1,然后检查该组(即A)的所有Col2是否 均为1。在此示例中,所需的输出为:

[A, C]
Run Code Online (Sandbox Code Playgroud)

(因为只有A和C的所有值都设置为1)。我该怎么做呢?

WeN*_*Ben 5

你的情况groupbyall

df.groupby('Col1').Col2.all().loc[lambda x : x ].index.tolist()
Out[350]: ['A', 'C']
Run Code Online (Sandbox Code Playgroud)

有无 groupby

df.loc[~df.Col1.isin(df.Col1[df.Col2.eq(0)]),'Col1'].unique()
Out[352]: array(['A', 'C'], dtype=object)
Run Code Online (Sandbox Code Playgroud)

从评论

cs95:df.loc[df['Col2'].astype(bool).groupby(df['Col1']).transform('all'), 'Col1'].unique()

  • df.loc [df ['Col2']。astype(bool).groupby(df ['Col1'])。transform('all'),'Col1']。unique()` (2认同)