Python Accumulate Values

3386
3
Jump to solution
09-15-2015 04:44 AM
ToddHenry1
Occasional Contributor

In another post, I found this python script that creates a running total.  I was able to modify it to do a running product, but I need to have the running product reset when the value of another field changes.

How might I modify this code to do that?

  • Calculate the accumulative value of a numeric field.
  • Expression:
  • accumulate(!FieldA!)
  • Expression Type:
  • PYTHON_9.3
  • Code Block:
  • total = 0
  • def accumulate(increment):
  • global total
  • if total:
  •   total *= increment
  • else:
  •   total = increment
  • return total

My data is similar to this

95

IDValue
1
19
2
25

The answer would be 1 = 81 and 2 = 25 in the 2nd row of each ID.

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
ToddHenry1
Occasional Contributor

Below is the code I ended up using with some help from Tech Support.

This goes in the code block:

total = 0

LocationID = 0

def accumulate(locID, Inc):

    global total, LocationID

    if locID != LocationID:

       total = 0

       LocationID = locID

    if total: total = total*Inc

    else: total = Inc

    return total

In the expression I use accumulate(!LocationID!,!IncField!)

The LocationID is my grouping Field and the IncField is the one that gets multiplied together.

View solution in original post

0 Kudos
3 Replies
FreddieGibson
Occasional Contributor III

Have you tried adding another global variable to store the value in the other field so that you can check to see if it changed? You'd also need to add another variable to the expression to pass in the id value.

ToddHenry1
Occasional Contributor

Below is the code I ended up using with some help from Tech Support.

This goes in the code block:

total = 0

LocationID = 0

def accumulate(locID, Inc):

    global total, LocationID

    if locID != LocationID:

       total = 0

       LocationID = locID

    if total: total = total*Inc

    else: total = Inc

    return total

In the expression I use accumulate(!LocationID!,!IncField!)

The LocationID is my grouping Field and the IncField is the one that gets multiplied together.

0 Kudos
DanPatterson_Retired
MVP Emeritus

Just like Freddie said ... for others following this

total

LocationID

in the posted solution are both global variables whose values get updated inside the scope of the def .  Globals...although generally not recommended... are useful should you need to persist an initial value so that it can be updated as the cursor is incremented

0 Kudos