3

I have a dataframe like this:

enter image description here

This is the final dataframe that I want:

enter image description here

I know I can use groupby to count, but it only gives me the total number. How can I break down into the count per 'True' and 'False'. and arrange like this?

Kent Shikama
  • 3,910
  • 3
  • 22
  • 55
Marlin
  • 111
  • 1
  • 11
  • 2
    `df.groupby(['ID', 'PASS'])['PASS'].size().unstack(fill_value=0).assign(Total=lambda x: x.sum(axis=1))` https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe – Alexander Dec 10 '19 at 03:07

2 Answers2

2
import pandas as pd

data = [['a', 'TRUE'], ['a', 'FALSE'], ['a', 'TRUE'], ['b', 'TRUE'], ['b', 'TRUE'], ['b', 'TRUE'],
    ['b', 'FALSE'], ['c', 'TRUE'], ['c', 'TRUE']]
df = pd.DataFrame(data, columns=['ID', 'PASS'])


df['value'] = 1
result = df.pivot_table(values='value', index='ID', columns='PASS', aggfunc='sum', fill_value=0)
result['Total'] = result.agg(sum, axis=1)
result
PASS    FALSE   TRUE    Total
ID          
a   1   2   3
b   1   3   4
c   0   2   2
mustnot
  • 159
  • 5
0

Another way to do it is by groupby and unstack, such that:

df = df.groupby(["ID","PASS"])['PASS'].count().unstack(fill_value=0)
df['total'] = df['FALSE']+df['TRUE']

desired result:

PASS    FALSE   TRUE    Total
ID          
a         1       2      3
b         1       3      4
c         0       2      2
adhg
  • 10,437
  • 12
  • 58
  • 94