Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. import arcpy
  2.  
  3. # return unique values from field
  4. # courtesy of arcpy cafe at https://arcpy.wordpress.com/2012/02/01/create-a-list-of-unique-field-values/
  5. def unique_values(table, field):
  6. with arcpy.da.SearchCursor(table, [field]) as cursor:
  7. return sorted({row[0] for row in cursor})
  8.  
  9. # workspace where the two point files reside
  10. arcpy.env.workspace = r"C:Users*****DocumentsArcGISDefault.gdb"
  11.  
  12. # reference to each point set
  13. pointset_1 = "pointset_1"
  14. pointset_2 = "pointset_2"
  15.  
  16. # add fields to one of them
  17. arcpy.AddField_management(pointset_1, "Distance", "DOUBLE")
  18. arcpy.AddField_management(pointset_1, "Nearest_FID", "LONG")
  19.  
  20. # create list of unique group values
  21. group_names = unique_values(pointset_1, "NAME")
  22.  
  23. # for each group
  24. for group in group_names:
  25. query_1 = "NAME = '" + group + "'"
  26. query_2 = "NAME <> '" + group + "'"
  27. temp_lyr_1 = "lyr1_" + group
  28. temp_lyr_2 = "lyr2_" + group
  29.  
  30. # select the group from pointset_1
  31. arcpy.MakeFeatureLayer_management(pointset_1, temp_lyr_1)
  32. arcpy.SelectLayerByAttribute_management(temp_lyr_1, "NEW_SELECTION", query_1)
  33.  
  34. # get all the values for OBJECTID in this group
  35. fc_id_list = unique_values(temp_lyr_1, "OBJECTID")
  36.  
  37. # select all in pointset_2 that is not in the group
  38. arcpy.MakeFeatureLayer_management(pointset_2, temp_lyr_2)
  39. arcpy.SelectLayerByAttribute_management(temp_lyr_2, "NEW_SELECTION", query_2)
  40.  
  41. # for each feature in the group (pointset_1)
  42. for fc_id in fc_id_list:
  43. query_1 = "NAME = '" + group + "' AND OBJECTID = " + str(fc_id)
  44. temp_lyr_3 = "lyr_" + str(fc_id)
  45.  
  46. # select only that feature
  47. arcpy.MakeFeatureLayer_management(temp_lyr_1, temp_lyr_3)
  48. arcpy.SelectLayerByAttribute_management(temp_lyr_3, "NEW_SELECTION", query_1)
  49.  
  50. # perform near analysis for that feature to the other groups in pointset_2
  51. arcpy.Near_analysis(temp_lyr_3, temp_lyr_2)
  52.  
  53. # according to ArcGIS docs this will automatically set non selected each time to -1
  54. # so we grab the data and insert it into our created fields.
  55. with arcpy.da.SearchCursor(temp_lyr_3, ["NEAR_DIST", "Distance", "NEAR_FID"]) as cursor:
  56. for row in cursor:
  57. arcpy.CalculateField_management(temp_lyr_3, "Distance", row[0], "PYTHON_9.3")
  58. arcpy.CalculateField_management(temp_lyr_3, "Nearest_FID", row[2], "PYTHON_9.3")
  59.  
  60. # you can write more to remove unwanted fields NEAR_DIST, NEAR_FID etc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement