IordanouGiannis
IordanouGiannis

Reputation: 4357

How can I count a specific value in group_by in 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.

Upvotes: 7

Views: 15917

Answers (1)

joris
joris

Reputation: 139142

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()

Upvotes: 15

Related Questions