user11509999
user11509999

Reputation:

Python DataFrame : Get count from a dataframe column based on condition?

            name              status
    0       alex                pass
    1       alex                pass
    2       alex                unknown
    3       marcus              pass
    4       marcus              fail
    5       anthony             fail
    6       paul                pass
    7       paul                unknown
    8       paul                fail
    9       paul                pass

if one the name column record has status = pass. I'm trying get count of status = pass

            name            count      
    0       alex              2   
    1       marcus            1     
    2       anthony           0       
    3       paul              2

Upvotes: 1

Views: 45

Answers (2)

jezrael
jezrael

Reputation: 862521

You can aggregate sum of boolean mask, because Trues are processing like 1:

df = df['status'].eq('pass').groupby(df['name']).sum().reset_index(name='count')
print (df)
      name  count
0     alex      2
1  anthony      0
2   marcus      1
3     paul      2

Upvotes: 1

yatu
yatu

Reputation: 88236

We can use pd.crosstab and index on the column of interest:

pd.crosstab(df.name, df.status)['pass'].reset_index()

      name  pass
0     alex     2
1  anthony     0
2   marcus     1
3     paul     2

       

Upvotes: 1

Related Questions