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

How can I calculate the sum of 3 values from each number in a pandas dataframe including the first number?

I have a dataframe as below:

        Datetime     Data      Fn
0   18747.385417  11275.0       0
1   18747.388889   8872.0       1
2   18747.392361   7050.0       0
3   18747.395833   8240.0       1
4   18747.399306   5158.0       1
5   18747.402778   3926.0       0
6   18747.406250   4043.0       0
7   18747.409722   2752.0       1
8   18747.420139   3502.0       1
9   18747.423611   4026.0       1

I want to calculate the sum of 3 values from each number in Fn and put the value in Sum.

My expected result is this:

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

        Datetime     Data      Fn     Sum
0   18747.385417  11275.0       0       0
1   18747.388889   8872.0       1       0
2   18747.392361   7050.0       0       1
3   18747.395833   8240.0       1       2
4   18747.399306   5158.0       1       2 
5   18747.402778   3926.0       0       2
6   18747.406250   4043.0       0       1
7   18747.409722   2752.0       1       1
8   18747.420139   3502.0       1       2
9   18747.423611   4026.0       1       3

>Solution :

df['Sum'] = df.Fn.rolling(3).sum().fillna(0)

Output:

       Datetime     Data  Fn  Sum
0  18747.385417  11275.0   0  0.0
1  18747.388889   8872.0   1  0.0
2  18747.392361   7050.0   0  1.0
3  18747.395833   8240.0   1  2.0
4  18747.399306   5158.0   1  2.0
5  18747.402778   3926.0   0  2.0
6  18747.406250   4043.0   0  1.0
7  18747.409722   2752.0   1  1.0
8  18747.420139   3502.0   1  2.0
9  18747.423611   4026.0   1  3.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