Tuesday, 23 October 2018

field calculator - Calculating centroids of polygon using ArcPy?


I am trying to calculate the centroids of a polygon and add the x- and y-coordinate to their respective fields:



arcpy.env.workspace = r"C:/..."

input_fc = "shapefiles/precincts_v.shp"
arcpy.AddField_management(input_fc, "X", "DOUBLE")
arcpy.AddField_management(input_fc, "Y", "DOUBLE")

arcpy.CalculateField_management(input_fc, "X", "!SHAPE.CENTROID@DECIMALDEGREES!.split()[0]", "PYTHON")
arcpy.CalculateField_management(input_fc, "Y", "!SHAPE.CENTROID@DECIMALDEGREES!.split()[1]", "PYTHON")

but I an invalid syntax error. Where is the mistake?



Edit: exact error message


Traceback (most recent call last):
File "C:\Users\mquentel\Dropbox\PLSS\CA voting data\Python\CONSTRUCT_merge_voting_and_census.py", line 17, in
arcpy.CalculateField_management(input_fc, "X", "!SHAPE.CENTROID@DECIMALDEGREES!.split()[0]", "PYTHON")
File "C:\Program Files (x86)\ArcGIS\Desktop10.4\ArcPy\arcpy\management.py", line 3360, in CalculateField
raise e
ExecuteError: ERROR 000539: SyntaxError: invalid syntax (, line 1)
Failed to execute (CalculateField).

Answer



Replace your Field Calculator lines with



arcpy.CalculateField_management(input_fc, "X", "!SHAPE.CENTROID.X!", "PYTHON_9.3")
arcpy.CalculateField_management(input_fc, "Y", "!SHAPE.CENTROID.Y!", "PYTHON_9.3")

Works for me with Decimal Degrees.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...