Comparing field values of two feature classes using ArcPy?

Comparing field values of two feature classes using ArcPy?

We are searching data for your request:

Forums and discussions:
Manuals and reference books:
Data from registers:
Wait the end of the search in all databases.
Upon completion, a link will appear to access the found materials.

I have an intermediate fc #1 that contains data that I would like to append to my production fc # 2(final output). When working with the data, I would only like to append data from my fc # 1that is not in fc # 2, to avoid duplicates, etc. My field that I would like to check isSRNumberI would like to only append from fc # 1 to fc # 2 whenSRNumberis not in fc # 2. Can this be done via ArcPy?

Maybe get values of fields from fc # 1 SRNumber store in list and write anything not in list to fc # 2?

Here is a Python toolbox tool I recently created that will insert all selected records from one fc/table into another fc/table. It does all of the field matching and validates the inputs to make sure the inputs are compatible types with matching geometry and spatial reference when applicable. It acts like copy/paste, except that it also works for StandAlone Tables (something ArcMap does not support when you want to Append from an FC to a Standalone table). It does not support inserts from a Standalone Table to an FC, but it supports all 3 other combinations (FC to FC, FC to Table, and Table to Table). It is very fast.

The original tool just inserted anything selected in the first FC/table, but I have modified it in the code below to add lines to gather all SRNumbers into a dictionary from fc 2 (the insertFC) and validate that any SRNumber in the inserttFC is skipped so that only the records from fc 1 (the FC) not found in the insertFC are inserted. (However, these modification have not been tested and you should first use it on a copy of your data to make sure it works before doing anything with your master data). I have added comments to note what changes I made to the original code just to solve the specific request in this post concerning the SRNumber behavior.

So create a new Python toolbox and insert the code below into it. Then add both fcs to your current map and select every feature in fc 1. Then run the tool and make the first FC your fc 1 and make the insert FC your fc 2. Close any open table view before running the tool, since there is a refresh problem that is Esri's fault (Append tool has the same problem) and after running the tool reopen the table view and you will see the newly inserted features selected. If you have an Editor session going the inserts will disappear without warning if you stop the edit session without saving the edits. But if you save the edits the inserts will be permanent.

import arcpy class Toolbox(object): def __init__(self): """Define the toolbox (the name of the toolbox is the name of the .pyt file).""" self.label = "Field Match Tools" self.alias = "" # List of tool classes associated with this toolbox = [InsertSelectedFeaturesOrRows] class InsertSelectedFeaturesOrRows(object): def __init__(self): """Define the tool (tool name is the name of the class).""" self.label = "Insert Selected Features or Rows" self.description = "" self.canRunInBackground = False def getParameterInfo(self): """Define parameter definitions""" # First parameter param0 = arcpy.Parameter( displayName="Input Layer or Table View", name="in_prim_table", datatype="GPTableView", parameterType="Required", direction="Input") # Second parameter param1 = arcpy.Parameter( displayName="Output Layer or Table View", name="out_table", datatype="GPTableView", parameterType="Required", direction="Input") # Third parameter param2 = arcpy.Parameter( displayName="Number of Copies to Insert", name="number_of_row_copies", datatype="GPLong", parameterType="Required", direction="Input") param2.value = 1 # Fourth parameter param3 = arcpy.Parameter( displayName="Derived Layer or Table View", name="derived_table", datatype="GPTableView", parameterType="Derived", direction="Output") param3.parameterDependencies = [] param3.schema.clone = True params = [param0, param1, param2, param3] return params def isLicensed(self): """Set whether tool is licensed to execute.""" return True def updateParameters(self, parameters): """Modify the values and properties of parameters before internal validation is performed. This method is called whenever a parameter has been changed.""" return def updateMessages(self, parameters): """Modify the messages created by internal validation for each tool parameter. This method is called after internal validation.""" if parameters[1].value: insertFC = parameters[1].value strInsertFC = str(insertFC) if parameters[0].value and ' 0: print("{} has {} {}{} selected".format(, len(selection_set.split(';')), 'feature' if ' 'Geometry' and insertFCfield.editable == True and not ( in matchedFields)): matchedFields.append( break elif (FCfield.type == 'Geometry' and FCfield.type == insertFCfield.type): matchedFields.append("[email protected]") break elif insertFCfield.type == "OID": oid_name = if len(matchedFields) > 0: # Print the matched fields list print("The matched fields are: {}".format(matchedFields)) arcpy.AddMessage("The matched fields are: {}".format(matchedFields)) copies = parameters[2].value print("Making {} {} of each {}".format(copies, 'copy' if copies == 1 else 'copies', 'feature' if ' 1: whereclause = oid_name + ' in="" ('="" +="" ','.join(map(str,="" oid_list))="" +="" ')'="" if="" len(oid_list)=""> 0: # arcpy.AddMessage(whereclause) # Switch feature selection arcpy.SelectLayerByAttribute_management(FCLyr, "CLEAR_SELECTION", "") arcpy.SelectLayerByAttribute_management(insertFCLyr, "NEW_SELECTION", whereclause) print("Successfully inserted {} {}{} into {}".format(len(oid_list), 'feature' if '

As @PolyGeo mentioned, a search cursor proceeded by an insert cursor will do the trick here. First nab all the values from fc3 with a little python list comprehension and search cursor. Then iterate through the rows in fc2. Check the values in your check field against your list. If the value isn't in your list, insert the fc2 row into fc3.

The script assumes all the fields are exactly the same, and in the same order between the two feature classes, and that you're working with 10.1 or later.

import arcpy #input feature class fc2 = r"C:	emp	emp.gdbfc2" #target feature class fc3 = r"C:	emp	emp.gdbfc3" #check field checkField = "SRNumber" #Get list of values in field from target feature class checkValues = set ([r[0] for r in arcpy.da.SearchCursor (fc3, checkField)]) #Get list of fields fields = [ for f in arcpy.ListFields (fc2)] #Get index of check field index = fields.index (checkField) #Create insert cursor for fc3 to allow appending of rows inCursor = arcpy.da.InsertCursor (fc3, fields) #Create search cursor to iterate input feature class cursor = arcpy.da.SearchCursor (fc2, fields) #iterate for row in cursor: #Get value to check checkValue = row[index] #Check if value is in target fc if checkValue in checkValues: #skip if value is in target fc continue #Insert row otherwise inCursor.insertRow(row) #Clean up del cursor del inCursor

Untested - there may be a spelling mistake or two or three. Happy Pythoning!


  1. Fitzhugh

    You are wrong. I'm sure. I propose to discuss it. Write to me in PM, speak.

  2. Willesone

    At me a similar situation. I invite to the discussion.

  3. Shakajora

    Granted, this is a funny answer

  4. Shaktilar

    Sorry, I too would like to express my opinion.

  5. Abd Al Qadir

    Please tell me - where can I read about this?

  6. Balen

    I believe you were wrong. I'm sure. I propose to discuss it. Write to me in PM, speak.

  7. Devonn


Write a message