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.
Just use a searchcursor if you want to read values from a selection, or you could call the summary statistics tool.
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)
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.