ArcGIS – Using a Loop in a Python Expression to Stack Labels While Avoiding Zero Value Attributes

arcgis-desktoparcmapexpressionlabelingpython-parser

I have a number of point features in a map in ArcMap 10.6 that I would need to label based on information form three fields (Test1, Test2 and Test3) with numeric values. The labels from these 3 fields would have to be stacked. And each of these labels would have to appended with a date text. The format of the label would be something like this;

enter image description here

Some of the records in these fields contain zero values and so it would be required to loop through these fields and skip the zero values. That is not to have them displayed in the label. Currently I have the following scripts to work with;

-script to stack labels
-This does not skip through zero values

def FindLabel ([Test1] , [Test2] , [Test3]):
      return "05/10/2018" + " - " + [Test1] + "\r\n" + "05/10/2018" + " - " + [Test2] + "\r\n" + "05/10/2018" + " - " + [Test3]

-script to skip "0" values in the fields and stacks the labels, however does not append text string to each attribute value.

def FindLabel ( [Test1] , [Test2] , [Test3] ):
  fields =  ([Test1] , [Test2] , [Test3]) 
  label = ""
  for field in fields:
    if field == "0":
      continue
    else:
      label = label + field + "\n"
  return label

Is there a way achieve this using a python label expression in ArcMap 10.6

Best Answer

You can use List comprehension with an if statement and then join the list elements together to a string with newline in between:

def FindLabel ( [Test1],[Test2],[Test3] ):
  values = [Test1],[Test2],[Test3]
  date = "05/10/2018"
  labellist = ["{0} - {1}".format(date, value) for value in values if value != '0']
  label = "\n".join(labellist)
  return label

enter image description here

Related Question