简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM