I haven't been able to find any bit of code that does this successfully. I need to delete some fields in a table that I'm modifying using a script I'm writing. I don't want the fields to be left on the table, but I'm pretty sure that I need the fields to calculate the centroids. I haven't found a way of calculating parcel centroids that works without adding a field to a table. I want the xCentroid and yCentroid fields to be calculated, and I want to delete those fields at the end of the script. Here the code I'm using.
try:
# Set environment settings
arcpy.env.workspace = "U:/JackBuildingFootprints.gdb"
# Set local variables
inFeatures = "parcelsCopy"
xCentroid = "xCentroid"
yCentroid = "yCentroid"
fieldPrecision = 18
fieldScale = 11
# Add fields Remember to delete fields later. Get help with that
arcpy.AddField_management(inFeatures, xCentroid, "DOUBLE",
fieldPrecision, fieldScale)
arcpy.AddField_management(inFeatures, yCentroid, "DOUBLE",
fieldPrecision, fieldScale)
# Calculate centroid
arcpy.CalculateField_management(inFeatures, xCentroid,
"!SHAPE.CENTROID.X!",
"PYTHON_9.3")
arcpy.CalculateField_management(inFeatures, yCentroid,
"!SHAPE.CENTROID.Y!",
"PYTHON_9.3")
except Exception:
e = sys.exc_info()[1]
print(e.args[0])
-
Do you mean creating point file, depicting centroids?FelixIP– FelixIP2016年02月16日 20:00:24 +00:00Commented Feb 16, 2016 at 20:00
-
1You'll probably need to add more details, like the fields that you both want to and don't want to delete, and how they relate to centroids, and how you're generating centroids.Vince– Vince2016年02月16日 20:38:48 +00:00Commented Feb 16, 2016 at 20:38
-
Point taken I'll edit that in now.user66821– user668212016年02月16日 20:49:31 +00:00Commented Feb 16, 2016 at 20:49
-
1While CalculateField can do the job in two passes, it would be faster to use a DA UpdateCursor and make just one pass though the table, updating two fields at a time. Are you doing anything with these values before deleting them (with DeleteField_management)?Vince– Vince2016年02月16日 21:38:37 +00:00Commented Feb 16, 2016 at 21:38
-
I'm using them to draw a building footprint - hopefully. I didn't know DA update cursor did that. I'll work that in. Is there a way to get centroid values without creating a field?user66821– user668212016年02月17日 21:53:20 +00:00Commented Feb 17, 2016 at 21:53
2 Answers 2
You can delete fields with arcpy using DeleteField_management tool. More info on how to use tool can be found here.
Esri has provided How To: Calculate feature centroids:
Feature centroids can be calculated in several ways. Depending on how the centroid needs to calculated, there are several possible methods: calculate the features' central XY coordinates, use the Feature to Point tool, or use Python to retrieve centroid coordinates.
It includes sample code to "Use Python to calculate and build centroid points".