简体   繁体   中英

How do I do a sum in python for n+(n+12)+(n+24)+(n+36) and then for (n+1)+(n+13)+(n+25) and so on until reaching n+12?

So lets say I have monthly data and I am trying to find a type of monthly change but the monthly change I want would be the following having this data frame the one I have is much bigger having every month from 2010 to 2019.

axis   Month Date    Value
1       1-2012        10 
2       2-2012        11
3       3-2012        15 
4       1-2013        12
5       2-2013        13
6       3-2013        17
7       1-2014        15
8       2-2014        16
9       3-2014        20

I want to arrive to an output such as

axis  value_sum  
1.    37 
2.    40 
3.    52

1.which is equal as the sum of axis(1+4+7) 2.which is equal as the sum of axis(2+5+8) 3.which is equal as the sum of axis(3+6+9)

so at the end I will have just 12 numbers as an output. Iv been trying to do this as with def and defining a function but when getting to this part I simply dont know what to do.

I actually am pretty new with managing data frames with python/pandas so I would appreciate the help.

Assuming 'Month Date' is a string, group by quarter (extracted by .str[:1] ) and sum:

df['Value'].groupby(df['Month Date'].str[:1]).sum()

If first part is a month (can be two digit):

df['Value'].groupby(df['Month Date'].str.split('-').str.get(0)).sum()

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