Check if all the members of a group has same value then get all of them in one dataframe

Viewed 145

I have a large data frame like below:

Letter      Action
a       Do
b       Do
b       Do
b       Do
b       Do
c       Do
c       Don’t
c       Don’t
c       Don’t
c       Do
c       Don’t
c       Don’t
c       Don’t
c       Do

I need to get all the letters which action is Do for all rows.

My desired output would look like this:

Letter      Action
a       Do
b       Do
b       Do
b       Do
b       Do

I tried

df1 = df[(df.groupby('Letter', as_index=False).Action.nunique().eq(1))]

But I can not get what I need. I would be thankful if anyone could help.

1 Answers

Try with transform

df1 = df[(df.groupby('Letter').Action.transform('nunique').eq(1))]

For improvement

df1 = df[(df.Action.eq('Do').groupby(df['Letter']).transform('all')]
Related