0

I am trying to generate a script that executes a Spatial Join between specific shapefiles. However the only values that are added to the result feature are the first and last in the list of shapefiles to join. I have tried different approaches, however the result is always the same.

Spatial join for multiple shapefiles (loop) exposes the same problem, however I have not been able to identify the way it was solved.

This is the code:

# Shapefiles to join
selfc = ['tertiary_roads_CO_m_nonoise.shp',
         'tertiary_roads_NOX_m_nonoise.shp', 
         'tertiary_roads_PM10_nonoise.shp',
         'tertiary_roads_PM25_nonoise.shp',
         'tertiary_roads_SO2_nonoise.shp']

# Define target feature as the first element in the selfc list
targetFeature = selfc[0]

joinFeatures  = selfc[1:]
outfc = os.path.join(outdir, "testSpatialJoin")

for feature in joinFeatures:
    #Run the Spatial Join tool
    arcpy.SpatialJoin_analysis(targetFeature, feature, outfc, "JOIN_ONE_TO_MANY", "KEEP_ALL")

Result: Just the last Shapefile in the selfc list is joined to the Target Feature.

enter image description here

1
  • 2
    You need to use the output of each join as input to the next. But it would be easier to merge all joinfeatures then join once
    – Bera
    Commented Dec 9, 2021 at 17:46

1 Answer 1

0

It has finally been solved by saving the result of each iteration (as suggested by @BERA) in an arcpy.Point object, and at the end of the For loop copying each point object generated in a new Feature.

# Shapefiles to join
selfc = ['tertiary_roads_CO_m_nonoise.shp',
         'tertiary_roads_NOX_m_nonoise.shp', 
         'tertiary_roads_PM10_nonoise.shp',
         'tertiary_roads_PM25_nonoise.shp',
         'tertiary_roads_SO2_nonoise.shp']

# Define target feature as the first element in the selfc list
targetFeature = selfc[0]

joinFeatures  = selfc[1:]
outfc = os.path.join(outdir, "testSpatialJoin")

for feature in joinFeatures:
    #Run the Spatial Join tool
    targetFeature = arcpy.SpatialJoin_analysis(targetFeature, feature, arcpy.Point, "JOIN_ONE_TO_ONE", "KEEP_ALL")

# Copies feature from the iteration to a new feature class.
arcpy.CopyFeatures_management(targetFeature, outfc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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