Home > OS >  Calculating mean of column based on the occurence of a number in another column Pandas dataframe Pyt
Calculating mean of column based on the occurence of a number in another column Pandas dataframe Pyt

Time:12-03

I've got a Pandas dataframe like the one below. What I'm trying to do is calculating the mean of column s2, for every time that '5' occures in s1.

s1  s2
5   0.5
1   0.43
5   1
5   1

In this case, 5 occures three times, so we take the average over 0.5 1 1=0.83. Can someone help me to calculate this? Thanks!

CodePudding user response:

Try this

df[df['s1']==5]['s2'].mean()

CodePudding user response:

mean = df.loc[df['s1'] == 5, 's2'].mean()

output:

0.8333333333333334
  • Related