Warm tip: This article is reproduced from stackoverflow.com, please click
pandas python-3.6

Group values together in Pandas column, then filter values in another column

发布于 2020-03-27 10:23:39

Pandas Dataframe looks like so:

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

I wanted to group all together in Col1, then check Col2 to see whether all values for that group i.e. A are 1. In this example the desired output would be:

[A, C]

(because only A and C have all values set to 1). How do I do this?

Questioner
pymat
Viewed
32
YOBEN_S 2019-07-03 22:49

In your case groupby with all

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

Or without groupby

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

From the comment

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