user3668129
user3668129

Reputation: 4820

how to get percentage of elements which equal to string value

How can I get the percentage of by group (name) for t_results equals to "ok" ?

    name   t_result
0   aaa    ok   
1   aaa    err_1
2   bbb    err_1
3   bbb    ok
4   aaa    err_2
5   aaa    ok


name, percentage
aaa   0.5
bbb   0.5

Upvotes: 2

Views: 78

Answers (1)

jezrael
jezrael

Reputation: 862761

You can use mean of boolean mask, compared by Series.eq, convert to 0, 1 by Series.view or Series.astype and aggregate by df['name'] as Series:

df1 = (df['t_result'].eq('ok')
                     .view('i1') # .astype(int)
                     .groupby(df['name'])
                     .mean()
                     .reset_index(name='percentage'))
print (df1)
  name  percentage
0  aaa         0.5
1  bbb         0.5

Solution with new column and aggregate by column name name:

df1 = (df.assign(percentage = df['t_result'].eq('ok').view('i1'))
         .groupby('name', as_index=False)
         .mean())

Upvotes: 2

Related Questions