Calculate statistics for selected features and pass to a variable

1249
5
05-21-2021 07:15 AM
Status: Closed
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.

5 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!

ShaunWalbridge
Status changed to: Closed

Thanks for your idea! Based on the comments in this thread, it looks like this issue is addressable with a moderate amount of Python code directly using ArcPy, and is also possible using mechanisms like SeDF or plain pandas for performing the summarization. Based on that, will close this issue because the specific need can be addressed without a new specialized tool to solve it. Let us know if see any other areas that Python in ArcGIS can use enhancement.