Search code examples
pythongisarcpy

Writing lat/long geometries to a feature class field


I have a point feature class with over 80 million features that need to have fields added to include both the lat/long coordinates in two different fields. While it is easy to calculate this in ArcMap, I need to write a script that will write both to the table then round to within 3 of the decimal point. I have tried using both InsertCursor and UpdateCursor and have failed to be able to write to the fields. However when I use the SearchCursor I can retrieve the values I am just unable to write them to the fields.

Here's what I am working with so far:

import arcpy

from arcpy import env 
env.workspace = 'C:\Users\Testing'
env.overwriteOutput = True

inFeatures = "ras2point.shp"
cursor = arcpy.da.InsertCursor(inFeatures, ["SHAPE@X"])
for row in inFeatures:
     X = row[0]
     cursor.insertRow([X])

del row
del cursor   
print 'FINISHED'

Solution

  • You were on the right track with the UpdateCursor. If you haven't already added the XY fields, then you can do that with the script and set the field_scale parameter (number of decimal places) to 3 or round the values themselves. Then just make sure to include the new XY fields when you create the cursor.

    import arcpy
    
    from arcpy import env 
    env.workspace = 'C:\Users\Testing'
    env.overwriteOutput = True
    
    inFeatures = 'ras2point.shp'
    arcpy.AddField_management(inFeatures, 'X', 'DOUBLE', 8, 3)
    arcpy.AddField_management(inFeatures, 'Y', 'DOUBLE', 8, 3)
    with arcpy.da.UpdateCursor(inFeatures, ['SHAPE@X', 'SHAPE@Y', 'X', 'Y']) as cursor:
        for row in cursor:
            row[2] = round(row[0], 3)
            row[3] = round(row[1], 3)
            cursor.updateRow(row)
    
    print 'FINISHED'