[GIS] Automating polygon mergers with ArcPy

appendarcpymerge

This is the first real world python program am trying to write. I am trying to create a scrip that takes a shapefile that has n polygons with an integer formatted date (e.g. yyyymmdd or 6/24/2014 is 20140624) attribute and returns a shapefile which has a single polygon for each date, and that polygon is the summation of all polygons with that date or earlier. Additionally I need the polygon to retain the the attributes of the most recent polygon.

My initial thought was to manually sort the attribute table form most recent to oldest and have something like this to do the rest:

import arcpy
form arcpy import env
import shapefile

w = shapefile.Writer()
# Create a list of all off the features in the shapefile.
def generate_working_list(a):
    env.workspace = "a"
    wl = arcpy.ListFeatureClasses()

# copy the oldest polygon, merge it with the next oldest, copy the newly created polygon, repeat 
def aggregate(wl):
    twl = []
    fl = []
    wl[-1].append(twl)
    wl[-1].append(fl)
    wl.pop()
    while len(wl) > 1:
         wl[-1].append(twl)
         '''Dissolve/ merge twl'''
         twl[0].append(fl)
         wl.pop()
    swl[0].append(twl)
    arcpy.Append_management(twl, fl) '''I think that this is the right tool to use'''
    twl[0].append(fl)
    return fl
    w.save("Merged")

Best Answer

There are several ways to approach this: using Select Layer By Attributes (Data Management) or with a SearchCursor. I often prefer to use the SearchCursor with logic rather than Select by Attributes with a SQL statement.

First, enter a search date which will be used to determine the date cutoff for the merge and dissolve:

searchDate = 20130101

Create an empty list which will store the feature geometry objects:

mergeList = []

Start a SearchCursor and define the date field and the feature geometry with a shape token 'SHAPE@':

with arcpy.da.SearchCursor(fc, ['date', 'SHAPE@']) as cursor:

Loop through the individual features in the shapefile:

for row in cursor:

Set the logic so that any date less than or = to the search date gets added to the mergeList:

if row[0] <= searchDate:
    mergeList.append(row[1])

Merge all of the features in mergeList and save output to in_memory workspace:

arcpy.Merge_management(mergeList, 'in_memory\myMerge')

Finally, dissolve the polygons and save to disk:

arcpy.Dissolve_management('in_memory\myMerge', outfc)

enter image description here


import arcpy

fc = r'C:\temp\tempSHP.shp'
outfc = r'C:\temp\outSHP.shp'

searchDate = 20130101

mergeList = []

with arcpy.da.SearchCursor(fc, ['date', 'SHAPE@']) as cursor:
    for row in cursor:
        if row[0] <= searchDate:
            mergeList.append(row[1])

arcpy.Merge_management(mergeList, 'in_memory\myMerge')
arcpy.Dissolve_management('in_memory\myMerge', outfc)