Calculate statistics for selected features and pass to a variable

574
4
05-21-2021 07:15 AM
Status: Open
d484648
New Contributor III

The analysis.Statistics tool calculates statistics for selected rows but puts the value in a CSV table. I want to be able to calculate the sum of values in a field for selected rows and then use the sum elsewhere in my Python Script.

4 Comments
DuncanHornby

Just use a searchcursor if you want to read values from a selection, or you could call the summary statistics tool.

d484648

Thanks for the reply.

The summary statistics tool generates a CSV file for each sum. I don't need that.

I'll have to look up how to read and create a running sum of values from a selection using a searchcursor.

MarkBryant

Wrap the summary statistics in a function.

def calculate_field_statistics(in_table, field, statistics_type='SUM'):
    """ Run the Summary Statistics on a field in a table and return the result."""
    try:
        # Create the temporary stats result table
        stats_table = arcpy.CreateUniqueName('stats', 'in_memory')
        # The output field is statistics_type underscore field name
        stats_field = "{}_{}".format(statistics_type, field)
        # Run Summary Statistic
        arcpy.analysis.Statistics(in_table, stats_table, [[field, statistics_type]])
        # Return the first value from the stats_table
        return arcpy.da.SearchCursor(stats_table, stats_field).next()[0]
    finally:
        # Delete the stats table
        if arcpy.Exists(stats_table):
            arcpy.management.Delete(stats_table)

 

d484648

This is great, thanks!