Select to view content in your preferred language

List of Compounding Months - Python

663
5
02-14-2018 04:46 AM
Business_IntelligenceSoftware
Regular Contributor

I'm not sure if compounding is the right word for what I'm asking; but, is it possible to make a python list of compounding/cumulative months? For example, [Jan, Jan+Feb, Jan+Feb+Mar]. I want to use this to help me show customer growth from month to month. I've looked online, but can't find any examples of this. Is it possible? 

 

Tags (2)
0 Kudos
5 Replies
DanPatterson_Retired
MVP Emeritus

A cumulative sum... the easiest is to use the builtin cumsum from numpy... a demonstrate using 1 through 12 assuming... numpy is builtin and just needs to be imported in your scripts.

import numpy as np

a = np.arange(1,13)

c_sum = np.cumsum(a)

c_sum

array([ 1,  3,  6, 10, 15, 21, 28, 36, 45, 55, 66, 78], dtype=int32)

Another example

 b = np.random.randint(1, 4, size=12)

b

array([3, 3, 1, 3, 3, 2, 2, 2, 2, 3, 1, 2])

np.cumsum(b)

array([ 3,  6,  7, 10, 13, 15, 17, 19, 21, 24, 25, 27], dtype=int32)

or as a simple function

 
sum = 0
for i in b:
    print(sum)
    sum += i
print(sum)

0
3
6
7
10
13
15
17
19
21
24
25
27
Business_IntelligenceSoftware
Regular Contributor

Thanks for responding so quickly. I tried your first example, but the IDE says that "array" and "int32" are not defined. Also is line 7 from example 1 only supposed to say "c_sum"?

0 Kudos
DanPatterson_Retired
MVP Emeritus

That was a demonstration of what to do

  • import numpy as np  #  this is the python module that is needed
  • variable 'a' ... I made an array of data to demonstrate the processes
  • variable 'c'  .... I used one of the built-in function of numpy ... specifically 'cumsum' to get the result.  In python, when I imported numpy as np... np is now the numpy module with a 'nickname'.  I use 'module.function' to get a result.  In other words.... use the numpy cumulative sum function to get a cumulative sum  of variable 'a'.....therefore   c = np.cumsum(a)
  • the second example... was just another example...
  • the third example... is just an example of how to do cumulative sums the old-school way

That pretty well 'sums' it up from start to finish... cumulatively

JoshuaBixby
MVP Esteemed Contributor

I am not sure which version of Python you are using (2.x or 3.x), but accumulate was introduced in Python 3.2 if you are using Python 3:

>>> from itertools import accumulate
>>> l = [3, 3, 1, 3, 3, 2, 2, 2, 2, 3, 1, 2]
>>> list(accumulate(l))
[3, 6, 7, 10, 13, 15, 17, 19, 21, 24, 25, 27]
>>>
DanPatterson_Retired
MVP Emeritus

Good point... but If you are still using ArcMap (python 2.7)  The numpy version is available for both 2.7 and 3.6

0 Kudos