2

I have six fields in a table and I want to calculate a new field based on a formula using these six fields. Suppose the formula is simply:

newField = field1 + field2 + field3 + field4 + field5 + field6

how can I omit a field from this formula if the field value is 0? For example if for a row field1 = 0 then I want the new field to be calculated as:

newField = field2 + field3 + field4 + field5 + field6

Any field value can be 0 in any row. That field needs to be ommitted during calculation for that row. Multiple fields can also be 0, then all those fields are omitted. The fields cannot contain null values and are numeric. The formula needs to change conditionally based on the presence of 0 values. Is there anyway to do this with python or normally?

enter image description here

PS: Okay it looks like nothing needs to be changed in the above formula since adding 0 doesnt change anything. But its just an example. The actual formula is complex and if 0 value is used, the result will become false.

  • They are numeric thats why I have 0 values. – Salman Jan 25 '18 at 10:23
  • no there are no null values and there cant be. – Salman Jan 25 '18 at 10:31
  • 1
    Please Edit the question in response to requests for clarification. It's not fair to those who would answer to need to mine the comments for critical information. – Vince Jan 25 '18 at 10:50
  • Please also choose between using Field Calculator and straight Python, and whether you'd prefer to use these values in the expression or rebuild the elements before the formula or whether you want to conditionally change the formula. – Vince Jan 25 '18 at 10:58
2

The following Python expression in the Calculate Field tool works for me with 3 fields, just copy/paste and adapt the last if block to the 3 other fields:

def calc(f1, f2, f3):
    exp = ""
    if  f1 != 0:
        exp = f1
    if f2 != 0:
        if exp == "":
            exp =  f2
        else:
             exp += f2
    if f3 != 0:
        if exp == "":
            exp =  f3
        else:
            exp += f3
    return exp

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.