Computing in dataframe for multiple conditions pandas

Viewed 24

I have dataframe like this. I'm trying to compute the percentage of zone 6 for each team. I am unsure of how to perform this thank you.

2 Answers

The below code should work for you.

df = pd.read_excel('YOUR FILE HERE')
teams = df['team'].unique()
for i in teams:
    print(f'{i}:',(len(df[df['zone']==6])/len(df[df['team']==i])))

You can compute a boolean column of equality to 6, then get the mean per team to have the frequency, finally multiply by 100 for percentage:

df['zone'].eq(6).groupby(df['team']).mean().mul(100)
Related