简体   繁体   中英

Python count number of occurrence of a value in a dataframe column

I have a dataframe like this:

在此处输入图片说明

This is the final dataframe that I want:

在此处输入图片说明

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM