Hi there,
I am currently trying to work with python in ArcGIS Pro and I am stuck with the "Add Spatial Join"-Tool.
I got point-features (households) and lines (ducts) connected to them. I want to transfer some of the attributes from the households to the ducts feature class.
So first, I need to da a spatial join, right?
This is my code:
#code starts
import arcpy
import sys
def main():
arcpy.env.overwriteOutput = True
ducts = arcpy.GetParameterAsText(0)
houses = arcpy.GetParameterAsText(1)
try:
arcpy.AddMessage(f"Add Spatial Join:\n - Target-Layer: {ducts}\n - Join-Layer: {houses}")
arcpy.management.AddSpatialJoin(
target_features=ducts,
join_features=houses,
join_operation='JOIN_ONE_TO_ONE',
join_type='KEEP_ALL',
field_mapping='CID',
match_option='INTERSECT'
)
arcpy.AddMessage("Spatial Join Added successfully.")
except Exception as e:
arcpy.AddError(f"Error at 'Add Spatial Join': {e}")
if __name__ == "__main__":
main()
#code ends
When running this code, I get all the messages correctly and the tool finishes successfully but there is no spatial join added to my feature class. Is there an error in my code?
Thank you for your help!
Luca
Hi Luca,
Unless your point features are exactly on the line features they won't intersect. I would try changing the match option from INTERSECT to CLOSEST. eg.
Cheers,
Bryan
Is the first parameter to the tool (ducts) a layer in pro or a FC on disk?
It must be a layer in Pro since the spatial join is on a layer and not on the real data.
You can always use the Gp tool once and then copy the code from the History window.
Whenever you do anything involving a join or a selection on data, you need to make it a variable. otherwise, all the work gets done and then thrown into the ether.
This is my code:
#code starts
import arcpy
import sys
def main():
arcpy.env.overwriteOutput = True
ducts = arcpy.GetParameterAsText(0)
houses = arcpy.GetParameterAsText(1)
try:
arcpy.AddMessage(f"Add Spatial Join:\n - Target-Layer: {ducts}\n - Join-Layer: {houses}")
sjoin = arcpy.management.AddSpatialJoin(
target_features=ducts,
join_features=houses,
join_operation='JOIN_ONE_TO_ONE',
join_type='KEEP_ALL',
field_mapping='CID',
match_option='INTERSECT'
)
arcpy.AddMessage("Spatial Join Added successfully.")
except Exception as e:
arcpy.AddError(f"Error at 'Add Spatial Join': {e}")
if __name__ == "__main__":
main()
#code ends
You might have to add some lines telling it to actually add to the map, but I'd start with naming it and see what happens.