0

I want to compare each polygon from one shapefile with all the polygons from another shapefile.
When one polygon is geometrically identical to a polygon on the other shapefile, I want to copy the value of field "code" of the second shapefile to the field "code" of the first shapefile.
I wrote the following code:

fc1 = ur'D:\polygons1.shp'
fc2 = ur'D:\polygons2.shp'
fields = ['SHAPE@','code']
with arcpy.da.UpdateCursor(fc1,fields) as cur1:
    with arcpy.da.SearchCursor(fc2,fields) as cur2:
        for row1 in cur1:
            for row2 in cur2:
                row1[1] = row2[1] if(row1[0]==row2[0]) else ''
            cur1.updateRow(row1)

When I run the above code, the values from "code" are not copied plus there are no errors.
Any ideas?

  • 1
    The object equivalence test will always fail. You need to use a geometry comparison operator. If you do a spatial search of fc2, your program won't be O(N^2). – Vince Oct 19 '18 at 10:34
  • Have you considered using a spatial join? – Andy Oct 19 '18 at 19:57
  • @Andy I did use. I just wondering why the above code does not work. – Panos Oct 20 '18 at 19:41
1

As commented you cant compare geometries (SHAPE@) using equal to operator (==), you need a geometry comparison. Use the equals method:

Indicates if the base and comparison geometries are of the same shape type and define the same set of points in the plane.

import arcpy
arcpy.env.workspace = r'C:\Default.gdb' #Change
fc1 = 'polygons1' #Change
fc2 = 'Polygons2' #Change
fields = ['SHAPE@','code'] #Change

fc2_records = [i for i in arcpy.da.SearchCursor(fc2,fields)]

with arcpy.da.UpdateCursor(fc1,fields) as cursor:
    for row in cursor:
        for record in fc2_records:
            if row[0].equals(record[0]):
                row[1]=record[1]
                cursor.updateRow(row)

(If you have large datasets there will be faster ways. You could try merging the feature classes, sort by id and delete duplicates on shape field. Or do a select by location to find overlapping features and then pass these to the cursors.)

  • Probably ought to test for objectid1 != objectid2, but that means adding id columns to the fields list – Vince Oct 19 '18 at 12:10
  • Equality is not what I want to compare, Identicality is the one I want. @Vince OIDs between the two shapefiles are completely irrelevant. – Panos Oct 20 '18 at 19:46
  • Equals method will return true for identical geometries – BERA Oct 20 '18 at 19:50
  • Doh. The OID2>OID1 test is for two queries on a single source. – Vince Oct 20 '18 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.