I have to get the group which is having more "True" values than its "False" values from the given Dataframe:

Viewed 69
df = pd.DataFrame({'A':['group1','group1','group2','group1','group2',group1','group2','group2','group2','group1'],'B':['true','true','true','false','false','false','fasle','true','fasle','true']})

I tried to make it groupwise by using groupby function but that didn't work. Please help me out with this question.

EDIT: code

2 Answers

IIUC, you can use crosstab and query:

df = pd.DataFrame({'A':['group1','group1','group2','group1','group2','group1',
                                         'group2','group2','group2','group1'],
  'B':['true','true','true','false','false','false','false','true','false','true']})

pd.crosstab(df['A'],df['B']).query("true>false").index
#Index(['group1'], dtype='object', name='A')

If values in column B are boolean and not strings:

pd.crosstab(df['A'],df['B']).loc[lambda x:x[True]>x[False]].index

Longer code, but may be faster than pd.crosstab :

df.groupby(["A", "B"]).size().unstack().loc[lambda x: x.true.gt(x.false)].index

Index(['group1'], dtype='object', name='A')
Related