Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count a specific value in group_by in pandas?

Tags:

python

pandas

I have a dataframe and I use groupby to group it by Season. One of the columns of the original df is named Check and consists of True and False. My aim it to count the True values for each group and put it in the new dataframe.

import pandas as pd

df = ....
df['Check'] = df['Actual'] == df['Prediction']
grouped_per_year = df.groupby('Season')

df_2= pd.DataFrame()
df_2['Seasons'] = total_matches_per_year.keys()
df_2['Successes'] = ''
df_2['Total_Matches'] = list(grouped_per_year.size())
df_2['SR'] = df_2['Successes'] / df_2['Total_Matches']
df_2['Money_In'] = list(grouped_per_year['Money_In'].apply(sum))
df_2['Profit (%)'] = (df_profit['Money_In'] - df_profit['Total_Matches']) / df_profit['Total_Matches'] * 100.

I have tried:

successes_per_year = grouped_per_year['Pred_Check'].value_counts()

but I don't know how to get only the True count.

like image 470
IordanouGiannis Avatar asked Aug 26 '14 09:08

IordanouGiannis


1 Answers

For counting True, you can also use sum (as True=1 and False=0 when doing a numerical operation):

grouped_per_year['Pred_Check'].sum()
like image 175
joris Avatar answered Nov 14 '22 23:11

joris