Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do average in a regular interval

This might be a tough question though I thought it was easy.
So the problem is that I want to calculate the mean in N interval.

To simplify my data, the original data is like

Group Animal
1 6
3 5
2 4
4 nan
5 4
4 nan

And I would like to do average with each 3 steps,which means that the expecting df[Group] shows in three rows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Group
2.5 -->(1+4)/2
4 --> (3+5)/2
3 --> (2+4)/2

And the other problem is encountering NaN value, so if it has NaN value, we just calculate the value without NaN (and of course not showing NaN)
Thus, the ideal result in df[Animal] will be

Animal
6  --> (only 6, NaN cannot be calculated)
4.5  --> (5+4)/2
4 --> (4, NaN cannot be calculated)

shows in three rows
Any ideas to solve it, I appreciate it!

>Solution :

You can try with % : remainder

out = df.groupby(df.index%3).mean()
Out[127]: 
   Group  Animal
0    2.5     6.0
1    4.0     4.5
2    3.0     4.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading