Count for each element how often it occured

Viewed 52

I have a problem. I want to count for each element how often it occured and how often it was right, and how often it was wrong.

  • right: if (code == test)
  • wrong: if (code != test)

Dataframe

   customerId                text element  code  test
0           1  Something with Cat     cat     9     9
1           3  That is a huge dog     dog     8   999
2           3         Hello agian   mouse     7     7
3           3        This is a ca     cat     9   999
4           3       this is a cad     cat     9     9

Code

import pandas as pd
import copy
import re
d = {
    "customerId": [1, 3, 3, 3, 3],
    "text": ["Something with Cat", "That is a huge dog", "Hello agian", 'This is a ca', 'this is a cad'],
     "element": ['cat', 'dog', 'mouse', 'cat', 'cat'],
     "code": [9,8,7, 9, 9],
     "test": [9,999,7,999,9]
}
df = pd.DataFrame(data=d)
print(df)

What I want

element     count_complete count_true  count_false
cat         3              2           1
dog         1              0           1
mouse       1              1           0
1 Answers

Let us do crosstab

cond = df.eval('code == test')
pd.crosstab(df['element'], cond, margins=True).add_prefix('count_').drop('All')

col_0    count_False  count_True  count_All
element                                    
cat                1           2          3
dog                1           0          1
mouse              0           1          1
Related