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?
My data is similar to this
95
ID | Value |
---|---|
1 | |
1 | 9 |
2 | |
2 | 5 |
The answer would be 1 = 81 and 2 = 25 in the 2nd row of each ID.
Solved! Go to Solution.
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.
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.
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.
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