ArcGIS Pro – Creating Label Expression to Sum Attributes for Features in a Group

arcadearcgis-prolabeling

I have pipes that have been assigned to a group (1, 2, 3, 4, etc).
Each pipe also has a "Length" attribute.

I am working in Pro 3.2.0

For each pipe group, I want to have a single label that shows:

Group [X]

Total Footage: [Y]'

Typically, I would get all of my groups finalized and then get a table of summary stats by group number to join to the the feature class. I could then use the joined summary stats in the label expression.

But I want to know if it can be done on the fly in the label expression since my groups are subject to change and I want to avoid re running summary stats every time a pipe is reassigned to a different group.

I trying to make this work as a single label class – not a separate label class for each group.

Something like this, but it doesn't work.

var sumField = "mylengthfield"; // Replace with the actual field name you want to sum

// Use GroupBy() to group features based on a field
var groups = GroupBy($feature, "MyGroupField"); // Replace with the actual field for grouping

// Initialize the sum variable
var totalSum = 0;

// Loop through each group and sum the specified field
for (var group in groups) {
totalSum += Sum(group, sumField);}

return totalSum;

Best Answer

I was able to achieve this using the Python interpreter rather than Arcade due to the limited capabilities in the Arcade Profile for labeling.

I created random points with two groups and random values:

enter image description here

Then in the label settings, using the Python language, I changed the FindLabel function to:

import arcpy

def FindLabel ( [group_] ):
    with arcpy.da.SearchCursor(r"C:\SO\Data.gdb\Labels", ["value"], "group_ = '{0}'".format([group_])) as sc:
        total = 0
        for row in sc:
            total = total + row[0]
    return "Group Total ({0}): {1}".format([group_], total)

The function uses a search cursor to calculate the sum for the group value of the feature. Returning a string denoting the total:

enter image description here

If you're comfortable using Python rather than Arcade, then this would give you the desired sum for each group in the label class.

Related Question