I performed a spatial join based on point features that fell within polygons of interest. I now want to combine these features by polygon (field ID) and create a new field that combines information from one field. In the image below, I want to combine by TARGET_FID (ex: TARGET_FID = 7) and preserve the information from WS_Type to get a new field that would have, "Storage, Storage, Spring, Spring". I tried dissolve but the tool won't run because the "file is not supported".
1 Answer
This should get you fairly close:
import os, sys, arcpy
# change as needed
InFC = r'c:\your\path\to\JoinedFeatures.shp'
OutFC = r'c:\your\path\to\OutputTable.dbf'
ValDict = {} # new, empty dictionary
# Loop through all rows and populate the dictionary
with arcpy.da.SearchCursor(InFC,['TARGET_FID','WS_Type']) as SCur:
for ThisRow in SCur:
if ThisRow[0] in ValDict:
ValDict[ThisRow[0]].append(ThisRow[1]) # add this value to the end of the list
else:
ValDict[ThisRow[0]] = [] # make a new, empty, list for this TARGET_FID
ValDict[ThisRow[0]].append(ThisRow[1]) # add this value to the end of the list
# create a new table.. os.path.dirname is the folder, os.path.basename is the file name
arcpy.CreateTable_management(os.path.dirname(OutFC),os.path.basename(OutFC))
arcpy.AddField_management(OutFC,'TARGET_FID','LONG') # add target FID field
arcpy.AddField_management(OutFC,'WS_TYPE','TEXT',field_length = 255) # add nice big string field
# Loop through the dictionary and insert the new rows
with arcpy.da.InsertCursor(OutFC,['TARGET_FID','WS_Type']) as ICur:
for Val in ValDict:
JoinedString = ','.join(ValDict[Val]) # make this merged value into a string, comma delimited
ICur.insertRow((Val,JoinedString)) # insert the new row
I start by digesting the input rows, building a dictionary of lists (advanced topic) so that for each unique TARGET_FID there is a list of all the values in WS_Type, appending each string to the list.
After compiling into a dictionary loop through the dictionary making each list into a string using ','.join()
and insert the row into a new DBF file using an insert cursor.
Join Operation
option. In fact by using ONE_TO_ONE option with field mapping will give you what you are after. Have a look at gis.stackexchange.com/questions/178757/….