1

I’m looking to use the field calculator to calculate the number of ‘NOT NULL’ values in a subset of fields within an attribute table.

Field 1 Field 2 Field 3 Field 4 Field 5 Count
2 3 Null 1 Null 3

I have used the sum(filter(None,Args)) Python script to calculate the sum of the fields but I also want to calculate the number of not null values.

How can I do this?

EDIT

This is my existing code and error message

stack(!Signage_Adequate_Directional!,!Signage_Positive_Wording!,!Signage_Information!,!Signage_Welcome_Sign!,!Signage_Notice_Board!)

def stack(*args):  
    return len(filter(None, args))

Screenshot of calculate field error in Arcgis Pro

9
  • Change the sum() to len()
    – Vince
    Aug 4, 2021 at 20:58
  • These are ‘integers’. The len() function calculates the length of a string.
    – ColinB
    Aug 4, 2021 at 21:33
  • I get the following error message when i use len instead of sum - WARNING 002858: Certain rows set to NULL due to error while evaluating python expression: File "<string>", line 2, in stack
    – ColinB
    Aug 4, 2021 at 21:47
  • I seem to be allowed to calculate the length of all of the fields but not use the filter script to remove the null values before calculating the length.
    – ColinB
    Aug 4, 2021 at 21:52
  • 1
    Please edit the question. Comments do not have enough formatting options to legibly post large code blocks.
    – Vince
    Aug 5, 2021 at 11:53

1 Answer 1

0

One can use sum - Built-in Functions -- Python 3.x to count, just sum quantity one (1) instead of the value itself. For example, instead of sum([1,2,4]) one can use sum(1 for _ in [1,2,4]).

Although filter- Built-in Functions -- Python 3.x is a built-in function, it is arguably not Pythonic in its form. The Python documentation even states, "Note that filter(function, iterable) is equivalent to the generator expression...."

For this specific situation, the code block isn't necessary and a single Python expression will suffice.

# Count = 
sum(1 for value in (!Field1!, !Field2!, !Field3!, !Field4!, !Field5!) if value is not None)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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