Counting instances of non-zero fields in a record

2968
12
Jump to solution
07-29-2016 11:49 AM
DavidFox
New Contributor III

arcgis_table_snip.JPG

Referring to the table snippet above, each record has five fields for the last five fiscal years. The data will be either the number of that year or zero.

I need to calculate the Burns_5Yrs field based on the count of the number of non-zero years (in fields FY11 - FY15) in that record. The first three rows have examples manually entered. For example, the first record has activity in FY11 and FY14 so the result for Burns_5Yrs should be 2. The second row is also 2 and the third row is 4.

I've been doing this manually but now I have a table with 198 records so I'd like a programming solution, preferably in Python. Any help would be appreciated as I really don't know where to start.

Dave

Tags (1)
0 Kudos
12 Replies
JoshuaBixby
MVP Esteemed Contributor

The code block can be bypassed completely by using the sum() function directly in the expression block:

sum(1 for field in (!FY11!, !FY12!, !FY13!, !FY14!, !FY15!) if field)

DavidFox
New Contributor III

Thanks, this worked perfectly (after I used the actual field names instead of the aliases).

0 Kudos
DanPatterson_Retired
MVP Emeritus

Pandas was too clunky, so numpy in the field calculator... with pictures

Field_calc_numpy_01.png

The only thing to remember

  • always choose the python parser... and there is no way to set it to default
  • write a function... doesn't need to be fancy.
  • any imports are done once, so if numpy is already imported, it is only imported once
  • the function just contains the variables which will be used.  In this example, I used the field names without the ! marks.  There is no requirement for the variables to have the same field names
  • in the expression box, you put function name (ie 'r') plus the variables to pass.  The field names are being passed so enclose them in ! marks.
  • save your function for later use if you like

That's all