I developed a python script where the user inputs
- a polygon shapefile
- multiple point shapefiles
and within the script the polygon shapefile is divided into 1000mx1000m grid cells and the point shapefiles are joined to the polygon where the intersecting points per cell are counted.
The spatial join is done within a for loop and after the joins are finished, all fields that are not required and do not start with "Join" (like Join_Count, Join_Cou_1, ...) are deleted. Then, the output shapefile is stored.
I tested the code and everything was fine, but now I detected a huge issue. The order of the Join_Count, Join_Cou_1, Join_Cou_2, etc. does not correspond to the order in which the point shapefile were entered.
Below the input order and output order can be seen. I tried it multiple times, but it seems there is no logic behind the order, so not alphabetical, Input order, reverse order, or anything. It seems like it would be ordered randomly.
Bank -> Join_Count (Bank)
Kino -> Join_Cou_1 (Post)
Park -> Join_Cou_2 (Park)
Post -> Join_Cou_3 (Kino)
Why is this happening? Shouldn't it be in the same order as the input? Of course I cannot apply my code then, because the user would have to look manually which of the inputs are at which position.
Here is my code:
import arcpy studyarea = arcpy.GetParameterAsText(0) inputPoints = arcpy.GetParameterAsText(1) outputLocation = arcpy.GetParameterAsText(2) arcpy.GridIndexFeatures_cartography('in_memory\studyarea_grid', studyarea, 'INTERSECTFEATURE', 'NO_USEPAGEUNIT', "#", 1000, 1000) studyAreaGrid = arcpy.Clip_analysis('in_memory\studyarea_grid', studyarea, arcpy.Polygon) inputPoints_set = inputPoints.split(';') spatialJoin = studyAreaGrid for pointShp in inputPoints_set: spatialJoin = arcpy.SpatialJoin_analysis(spatialJoin, pointShp, arcpy.Polygon, 'JOIN_ONE_TO_ONE', 'KEEP_ALL', '', 'INTERSECT') fieldNameList =  fieldObjList = arcpy.ListFields(spatialJoin) for field in fieldObjList: if field.required == False: if not field.name.startswith('Join'): fieldNameList.append(field.name) arcpy.DeleteField_management(spatialJoin, fieldNameList) arcpy.CopyFeatures_management(spatialJoin, outputLocation)
I again tried to use fieldmappings, see code below. It works, meaning that only the Join_Count fields are passed on, but also the order is not the same as the Input order. Why does this happen? Should not fieldmappings work??
for pointShp in inputPoints_set: fieldmappings = arcpy.FieldMappings() fieldmappings.addTable(spatialJoin) fieldmappings.addTable(pointShp) for field in fieldmappings.fields: if field.required == False: if not field.name.startswith('Join'): fieldmappings.removeFieldMap(fieldmappings.findFieldMapIndex(field.name)) spatialJoin = arcpy.SpatialJoin_analysis(spatialJoin, pointShp, arcpy.Polygon, 'JOIN_ONE_TO_ONE', 'KEEP_ALL', fieldmappings, 'INTERSECT')