Groupby recall in pandas

Viewed 299

I have a dataframe as shown below.

Category     Actual       Predicted
1            1            1
1            0            1
1            0            0
1            0            0
2            1            1
2            1            0
2            0            0
2            0            1
3            1            1
3            0            1
3            0            0
3            0            1

From the above I would like to calculate recall for each categories 1, 2 and 3 as shown below.

Expected Output:

Category    Recall_for     Recall
1           0              66.7
1           1              100
2           0              50
2           1              50
3           0              33.3
3           1              100

Explanation:

For category = 1, Actual = 1, there are 1 case it is true (matching with Predicted), so recall = 1/1*100 = 100

For category = 1, Actual = 0, there are 3 cases and 2 only true (matching with Predicted), so recall = 2/3*100 = 66.7 and so on.

1 Answers

Compare both columns with Series.eq, set new column by DataFrame.assign, then aggregate mean (Trues are processing like 1) and last multiple and round values if necessary:

s = df['Predicted'].eq(df['Actual'])
df = (df.assign(Recall=s)
        .groupby(['Category','Actual'])['Recall']
        .mean()
        .mul(100)
        .round(1)
        .reset_index()
        .rename(columns={'Actual':'Recall_for'}))
print (df)
   Category  Recall_for  Recall
0         1           0    66.7
1         1           1   100.0
2         2           0    50.0
3         2           1    50.0
4         3           0    33.3
5         3           1   100.0
Related