AnsweredAssumed Answered

Python SearchCursor aggregate question

Question asked by LucasKaim on Aug 28, 2015
Latest reply on Sep 1, 2015 by Dan_Patterson

Hi Everyone,

 

I am trying to aggregate a point file by bird id and datetime. I want to aggregate based on two fields and then run Mean Center on each subset. The method below works. Is there a faster method or anything you would change? Thank you in advance.

 

 

def workflow(project_fc, workspace):
    """
    Method finds a unique bird and aggregates by day.
    Create a python set of all the unique combinations.
    Create a feature layer for each bird and day.
    Calculate mean center.
    """

    bird_d = "lyr"
    # Lists to store the output files for the geoprocess work flow.
    mean_list = []

    # fields stored in the fc.
    field_list = ["BirdId", "Date"]

    # Set to store bird date unique values.
    date_set = set()

    # The unique records are based off of two fields.
    # This is done using python sets.
    with arcpy.da.SearchCursor(project_fc, field_list) as cursor:
        for row in cursor:
            # Bird id.
            bird = row[0]
            # date field.
            date = row[1]
            # Create a set of bird id and date.
            # This will prevent duplicate dates from being added to the set.
            date_set.add((bird, date))

    # Iterate over the set and select by attribute.
    for j,i in enumerate(date_set):
        # Make a feature layer for bird id by day from the set.
        sql = "%s = '%s' AND %s = date '%s'" %(field_list[0], i[0], field_list[1], i[1])
        out_layer = arcpy.MakeFeatureLayer_management(project_fc, bird_d, sql)

        # MeanCenter_stats -----------------------------------------------------
        # Create the mean point for every bird id and date.
        mean_out = arcpy.MeanCenter_stats(bird_d, "mean_point" + str(j))

        # Append to the list lists.
        mean_list.append("mean_point" + str(j))

    # create a feature class.
    mean_all = arcpy.CreateFeatureclass_management(workspace, input, "POINT")

    # append all the points to this feature class.
    arcpy.Append_management(mean_list, mean_all[1].getOutput(0))

def main(test):
    workspace = r"C:\test.gdb"
    input = "test"
    metrics = workflow(project_fc=input,workspace=workspace)

if __name__ == "__main__":
    """
    Run the code as a stand alone application, else the main function
    does not get called.
    """
    main(test=False)

Outcomes