I want those customers present in the data frame which has more false value than true value .Any suggestion on how to achieve that

Viewed 60

The data frame :

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

Ouput : ['cust2']

3 Answers

First get counts by crosstab and then filter index values by columns with boolean indexing, for greater is used Series.gt:

df1 = pd.crosstab(df['A'], df['B'])
print (df1)
B      false  true
A                 
cust1      2     3
cust2      3     2

c = df1.index[df1['false'].gt(df1['true'])].tolist()
#if True, False are boolean
#c = df1.index[df1[False].gt(df1[True])].tolist()
print (c)
['cust2']]
df[df['B']=='false'].groupby(['A']).count().sort_values(by['A'],ascending=False).index[0]

Explanation: Take all values with only 'False', groupby 'A' and count. Now sort the value in descending order and get the first index('A') value.

It seems like the case of multi -indexing so you can use index to isolate the greater value :

list = list(dataframe.index[dataframe['false'].gt(dataframe['true'])])
Related