|
POST
|
Hi Please can someone help me with the where clause in my query below. Ideas very welcome Thanks scottaidh
... View more
04-11-2013
03:37 AM
|
0
|
2
|
1011
|
|
POST
|
Hi, I am running a select layer by attribute and location query on a feature layer of points made from a shapefile. I have been stuck for hours on the wording of it and would be grateful if some one would tell me how to do it because I have looked and tried many variations to no avail and there are so many suggestions but none seem to fit. I want the code to be "CRIME_INDE" <= 0.02 AND "UNVERSITY" = 1 but I can't get the right syntax in this case beacuse all the components are variables. Please could anyone offer any suggestions, it's really urgent and preventing me from progressing and I'll be happy to post up the resuts that work. Thanks scottaidh # import system modules import arcpy, os, arcpy from arcpy import env arcpy.env.overwriteOutput = True # get user supplied path, layers and fields path = arcpy.GetParameterAsText(0) # path is H:\working\Findsites.gdb cities = arcpy.GetParameterAsText(1) # cities Layer is cities Feature Layer cities.shp citiesL = "citiesL" crimeField = arcpy.GetParameterAsText(4) # crimeField is fieldname 'CRIME_INDE' SQL expression crimefieldindex = arcpy.GetParameterAsText(5) # crime index is CRIME_INDE and is a string 0.02 whereClause = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, crimeField), crimefieldindex) universityField = arcpy.GetParameterAsText(6) # universityField is fieldname 'UNIVERSITY' SQL expression universityfieldindex = arcpy.GetParameterAsText(7) # universityfieldindex is the UNIVERSITY field and is string integer 1 whereClause2 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, universityField), universityfieldindex) outfile = arcpy.GetParameterAsText(15) # ootput arcpy.MakeFeatureLayer_management(cities, citiesL) arcpy.SelectLayerByAttribute_management(citiesL, "SUBSET_SELECTION", '"' + whereClause + " <= " + crimefieldindex + " AND " + whereClause2 + " = " + universityfieldindex'') arcpy.CopyFeatures_management(citiesL, outfile) [\CODE}
... View more
04-10-2013
07:00 PM
|
0
|
10
|
3462
|
|
POST
|
Hi, I've written a script to import into Arc Tools (Toolbox) that finds suitable cities using a select by attribute and location query that is non hard coded and takes user input. All paths, shapefiles etc. are user input obtained when run as a tool in Arc Toolbox. In case it makes it clearer, the workspaces and shapefiles navigated to in GetParameterAsText are as follows- workspace H:\working\FindSites.gdb feature classes are "cities.shp", "counties.shp" and "interstates.shp" I can't get the script to generate the output table, CityList.shp as required and can't seem to spot why not. I get the following message after it has ran- Executing: EFLAgeneric H:\working\FindSites.gdb cities.shp 1 "CRIME_INDE" 1 "UNIVERSITY" counties.shp 2500 "AGE_18_64" 500 "NO_FARMS87" interstates.shp "30 Kilometers" CityList.shp Start Time: Tue Apr 09 00:34:29 2013 Running script EFLAgeneric... <type 'exceptions.NameError'>: name 'crimeField' is not defined Failed to execute (EFLAgeneric). Failed at Tue Apr 09 00:34:29 2013 (Elapsed Time: 0.00 seconds) The crimeField (and others) are defined in the script and don't know why the error message says it's not defined. Any help would be appreciated as I think I've run out of things to try. Thanks Scottaidh # extract features by attrtibute generic non hard coded version # scottaidh 9/4/13 # import system modules import arcpy, os, traceback, arcpy from arcpy import env arcpy.env.overwriteOutput = True # get user supplied path, layers and fields path = arcpy.GetParameterAsText(0) # path is H:\working\Findsites.gdb cities = arcpy.GetParameterAsText(1) # cities Layer is cities Feature Layer cities.shp citiesL = "citiesL" crimefieldindex = arcpy.GetParameterAsText(2) # crime index is CRIME_INDE and is a Double integer 0.02 whereClause = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, crimeField), crimefieldindex) crimeField = arcpy.GetParameterAsText(3) # crimeField is fieldname 'CRIME_INDE' SQL expression universityfieldindex = arcpy.GetParameterAsText(4) # universityfieldindex is the UNIVERSITY field and is DOUBLE integer 1 whereClause2 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, universityField), universityfieldindex) universityField = arcpy.GetParameterAsText(5) # universityField is fieldname 'UNIVERSITY' SQL expression counties = arcpy.GetParameterAsText(6) # countiesL is counties Feature Layer counties.shp countiesL = "countiesL" workforceindex = arcpy.GetParameterAsText(7) # workforce index is attribute of AGE_18_64 field and is a Double and is 25000 whereClause3 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(countiesL, workforceField), workforcefieldindex) workforceField = arcpy.GetParameterAsText(8) # workforceField is fieldname 'AGE_18_64' SQL expression farmfieldindex = arcpy.GetParameterAsText(9) # farmfieldindex is the NO_FARMS87 field and is Double integer is 500 whereClause4 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(countiesL, farmField), farmfieldindex) farmField = arcpy.GetParameterAsText(10) # farmField is fieldname 'NO_FARMS87' SQL expression interstates = arcpy.GetParameterAsText(11) # interstatesL Layer is the interstates Feature Layer interstates.shp # interstatesL = "interstatesL" nearestInterstate = arcpy.GetParameterAsText(12) # interstate WITHIN_A_DISTANCE linear unit # set output location outputLayer = arcpy.GetParameterAsText(13) # output layer CityList.shp targetFeatures = "cityListL" joinFeatures = "countiesL" # error trapping measures try: # make a layer from the cities feature class arcpy.MakeFeatureLayer_management(cities, citiesL) # select layer by location to interstates arcpy.SelectLayerByLocation_management(citiesL, "WITHIN_A_DISTANCE", interstates, nearestInterstate, "NEW_SELECTION") # from selection above select layer by attribute select "CRIME_IND" <= 0.02 AND "UNIVERSITY" = 1 arcpy.SelectLayerByAttribute_management(citiesL, "SUBSET_SELECTION", whereClause + " <= " + crimefieldindex + " AND " + whereClause2 + " = " + universityfieldindex) # write selected features to a new featureclass arcpy.CopyFeatures_management(citiesL, "SelectionCityLayer") # make counties feature layer arcpy.MakeFeatureLayer_management(counties,"countiesL") # select workforce and number of farms # new selection on counties layer countiesL "AGE_18_64" >= 25000 AND "NO_FARMS87" >= 500") arcpy.SelectLayerByAttribute_management("countiesL", "NEW_SELECTION", whereClause3 + " >= " + workforceindex + " AND " + whereClause4 + " >= " + farmfieldindex) # from selection above select cities intersecting counties arcpy.SelectLayerByLocation_management("citiesL", "INTERSECT", "countiesL", "", "SUBSET_SELECTION") # save selected features arcpy.CopyFeatures_management("citiesL", "tempCityList") # make temp cities list feature layer so that the output can be spatially joined to counties arcpy.MakeFeatureLayer_management("tempCityList",targetFeatures) # Generate NearTable_analysis to find closest interstate distance arcpy.GenerateNearTable_analysis(targetFeatures, interstatesFC, NearestInterstate, nearestInterstate) # join new city list layer to generated Near Table arcpy.AddJoin_management(targetFeatures, "OBJECTID", NearestInterstate, "IN_FID") #Run the Spatial Join tool, using the defaults for the join operation and join type arcpy.SpatialJoin_analysis(targetFeatures, joinFeatures, outputLayer, "#", "#", "#") # add field mappings later except: print arcpy.GetMessages() [\CODE]
... View more
04-08-2013
03:51 PM
|
0
|
0
|
472
|
|
POST
|
Thanks, The workspace is navigated to by the user when the tool is run but anyway its "H:\working\FindSites.gdb\cities" When the user runs the tool in ArcToolbox a pop-up menu appears similar to this with default paths etc. Input workspace H:\workspace\FindSites.gdb Input feature layer "cities.shp" Input min crimeindex 0.02 Input crimeindex field 'CRIME_INDE' Input min university 1 Input uniindexfield 'UNIVERSITY' Input output name "FoundSites.shp" I need the user to be able to change anything and even not put in any attribute selections. I'm tryin to write a user input non hard coded version (1) of the working hard-coded script (2) below. Do you see what I mean now? Any help would be very much appreciated. Scottaidh (1) Generic # script for user input tool based on select layer by location and attribute # parameters within feature classes are optional # scottaidh 8/4/13 # import system modules import arcpy, os, traceback, arcpy from arcpy import env arcpy.env.overwriteOutput = True # get user supplied path, layers and fields path = arcpy.GetParameterAsText(0) try : citiesFC = arcpy.GetParameterAsText(1) # cities Layer is cities Feature Layer crimefieldindex = arcpy.GetParameterAsText(2) # crime index is CRIME_INDE and is a Double integer whereClause1 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, crimeField), crimefieldindex) crimeField = arcpy.GetParameterAsText(3) # crimeField is fieldname 'CRIME_INDE' SQL expression universityfieldindex = arcpy.GetParameterAsText(4) # universityfieldindex is the UNIVERSITY field and is DOUBLE integer whereClause2 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, universityField), universityfieldindex) universityField = arcpy.GetParameterAsText(5) # universityField is fieldname 'UNIVERSITY' SQL expression outputlayer = arcpy.GetParameterAsText(6) # output layer name # select the attributes from citiesFC from user input prj = "" prj2 = "" if prj.find("CRIME_INDE")>=0: crimecount = 1 print 'using crime index' elif prj2.find("UNIVERSITY")>=1: unicount = 2 print 'using university status' # set field to determine where clause variables 1=crime 2=university 3=crime and university else: none selected usecityfield = crimecount + unicount # make feature layer from cities feature class arcpy.MakeFeatureLayer_management(citiesFC, "citiesL") if usecityfield == 1: arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", crimefieldindex) arcpy.CopyFeatures_management("citiesL", "citycrime") elif usecityfield == 2: arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", universityfieldindex) arcpy.CopyFeatures_management("citiesL", "cityuni") elif usecityfield == 3: arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", crimefieldindex + universityfieldindex) arcpy.CopyFeatures_management("citiesL", "citycrimeuni") else: # write selected features to a new featureclass arcpy.CopyFeatures_management("citiesL", "SUBSET_SELECTION") except: print arcpy.GetMessages() [\CODE] (2) Hard coded- # select layer by location and attribute import os, sys, traceback, arcpy arcpy.env.overwriteOutput = True try: citiesFC = r"H:\working\Findsites.gdb\cities" interstatesFC = r"H:\working\Findsites.gdb\interstates" countiesFC = r"H:\working\Findsites.gdb\counties" cityListFC = r"H:\working\Findsites.gdb\city_list" NearestInterstate = r"H:\working\Findsites.gdb\NearRoad" # setting variables for spatial join workspace = r"H:\working\Findsites.gdb" outWorkspace = r"H:\working\Findsites.gdb" targetFeatures = "cityListL" joinFeatures = "countiesL" outfc = r"H:\working\Findsites.gdb\FoundCities" arcpy.MakeFeatureLayer_management(citiesFC,"citiesL") arcpy.SelectLayerByLocation_management("citiesL", "WITHIN_A_DISTANCE", interstatesFC, "30 KILOMETERS", "NEW_SELECTION") arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", "UNIVERSITY = 1 AND CRIME_INDE <= 0.02") arcpy.MakeFeatureLayer_management(countiesFC,"countiesL") arcpy.SelectLayerByAttribute_management("countiesL", "NEW_SELECTION", "AGE_18_64 >= 25000 AND NO_FARMS87 >= 500") arcpy.SelectLayerByLocation_management("citiesL", "INTERSECT", "countiesL", "", "SUBSET_SELECTION") arcpy.CopyFeatures_management("citiesL", cityListFC) arcpy.AddField_management(cityListFC, "CITYNAME", "TEXT", "", "", "25") arcpy.AddField_management(cityListFC, "CRIMEINDEX", "DOUBLE", "", "", "") arcpy.AddField_management(cityListFC, "HAS_UNI", "TEXT", "", "", "3") arcpy.CalculateField_management(cityListFC, "CITYNAME", "!NAME!", "PYTHON") arcpy.CalculateField_management(cityListFC, "CRIMEINDEX", "!CRIME_INDE!", "PYTHON") arcpy.CalculateField_management(cityListFC, "HAS_UNI", "!UNIVERSITY!", "PYTHON") arcpy.DeleteField_management(cityListFC,["NAME", "LABEL", "CLASS"]) arcpy.DeleteField_management(cityListFC,["CRIME_INDE", "LABEL", "CLASS"]) arcpy.DeleteField_management(cityListFC,["UNIVERSITY", "LABEL", "CLASS"]) arcpy.MakeFeatureLayer_management(cityListFC,"cityListL") arcpy.GenerateNearTable_analysis("cityListL", interstatesFC, NearestInterstate, "30 Kilometers") arcpy.AddJoin_management("cityListL", "OBJECTID", NearestInterstate, "IN_FID") # spatially join the narrowed down city/road and counties layers remove unwanted fields and rename others # arcpy.SpatialJoin_analysis("cityListL", "countiesL", "H:/working/Findsites.gdb/FoundCities", "#", "#", "") # create new fieldMappings fieldmappings = arcpy.FieldMappings() fieldmappings.addTable(targetFeatures) fieldmappings.addTable(joinFeatures) NameFieldIndex = fieldmappings.findFieldMapIndex("NAME") fieldmap = fieldmappings.getFieldMap(NameFieldIndex) # Get the output field's properties as a field object field = fieldmap.outputField # Rename the field and pass the updated field object back into the field map field.name = "COUNTYNM" field.aliasName = "COUNTYNM" fieldmap.outputField = field # replace old field map in mappings object with new one fieldmappings.replaceFieldMap(NameFieldIndex, fieldmap) # delete fields no longer applicable s = fieldmappings.findFieldMapIndex("city_list_ID") fieldmappings.removeFieldMap(s) t = fieldmappings.findFieldMapIndex("city_list_POPULATION") fieldmappings.removeFieldMap(t) u = fieldmappings.findFieldMapIndex("city_list_TOTAL_CRIM") fieldmappings.removeFieldMap(u) v = fieldmappings.findFieldMapIndex("AREA") fieldmappings.removeFieldMap(v) w = fieldmappings.findFieldMapIndex("POP1990") fieldmappings.removeFieldMap(w) x = fieldmappings.findFieldMapIndex("POP_SQMILE") fieldmappings.removeFieldMap(x) y = fieldmappings.findFieldMapIndex("SQ_MILES") fieldmappings.removeFieldMap(y) z = fieldmappings.findFieldMapIndex("X") fieldmappings.removeFieldMap(z) a = fieldmappings.findFieldMapIndex("Y") fieldmappings.removeFieldMap(a) b = fieldmappings.findFieldMapIndex("X_1") fieldmappings.removeFieldMap(b) c = fieldmappings.findFieldMapIndex("Y_1") fieldmappings.removeFieldMap(c) d = fieldmappings.findFieldMapIndex("PERIMETER") fieldmappings.removeFieldMap(d) e = fieldmappings.findFieldMapIndex("GAVPRIMARY") fieldmappings.removeFieldMap(e) f = fieldmappings.findFieldMapIndex("NearRoad_OBJECTID") fieldmappings.removeFieldMap(f) g = fieldmappings.findFieldMapIndex("NearRoad_IN_FID") fieldmappings.removeFieldMap(g) h = fieldmappings.findFieldMapIndex("NearRoad_NEAR_FID") fieldmappings.removeFieldMap(h) #Run the Spatial Join tool, using the defaults for the join operation and join type arcpy.SpatialJoin_analysis(targetFeatures, joinFeatures, outfc, "#", "#", fieldmappings) # order and rename final output fields where appropriate arcpy.AddField_management(outfc, "INTERSTATEkm", "SHORT", "3", "1", "") arcpy.AddField_management(outfc, "COUNTY", "TEXT", "", "", "14") arcpy.AddField_management(outfc, "WORKFORCE", "LONG", "", "", "") arcpy.AddField_management(outfc, "FARMS", "LONG", "", "", "") arcpy.CalculateField_management(outfc, "INTERSTATEkm", "!NearRoad_NEAR_DIST!", "PYTHON") arcpy.CalculateField_management(outfc, "COUNTY", "!COUNTYNM!", "PYTHON") arcpy.CalculateField_management(outfc, "WORKFORCE", "!AGE_18_64!", "PYTHON") arcpy.CalculateField_management(outfc, "FARMS", "!NO_FARMS87!", "PYTHON") arcpy.DeleteField_management(outfc,["NearRoad_NEAR_DIST", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["COUNTYNM", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["AGE_18_64", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["NO_FARMS87", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["OBJECTID_1", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["Shape_Leng", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["Join_Count", "LABEL", "CLASS"]) arcpy.DeleteField_management(outfc,["TARGET_FID", "LABEL", "CLASS"]) except: # print geoprocessing messages if fails print "\n*** LAST GEOPROCESSOR MESSAGE (may not be source of the error)***"; print arcpy.GetMessages() print "Python Traceback Info: " + traceback.format_tb(sys.exc_info()[2])[0] print "Python Error Info: " + str(sys.exc_type)+ ": " + str(sys.exc_value) [\CODE]
... View more
04-08-2013
09:32 AM
|
0
|
0
|
560
|
|
POST
|
Hi, I'm writing a script for a toolbox that gets user input to run a select layer by attribute and location tool on a cities shapefile that contains two fields of interest, cime index (CRIME_IND) and university status (UNIVERSITY), both integers. The 1st part, select layer by attribute, results in a layer being saved (citiesL) with those attributes and is shown in the code below. I'm having problems in getting the user to define which attributes to select, none, one or more than one. If the user chooses to select only crime attributes ("CRIME_INDE" <= 0.02) then only those ones would be saved and if the user chooses to select crime and university status attributes ("CRIME_INDE" <=0.02 AND "UNIVERSITY" = 1) then both those sets of attributes would be saved to the layer file. Similarily, if the user does not fill in the required fields (by changing their default to nothing) then all the attributes of the cities layer would be effectively be saved to the layer file i.e. no selection by attribute. When I run the code in the toolbox it completes successfuly but no layer is saved (citiesL). I'm not sure where I'm going wrong with this and would appreciate any help. Thanks scottaidh
# script for user input tool based on select layer by location and attribute
# parameters within feature classes are optional
# scottaidh 8/4/13
# import system modules
import arcpy, os, traceback, arcpy
from arcpy import env
arcpy.env.overwriteOutput = True
# get user supplied path, layers and fields
path = arcpy.GetParameterAsText(0)
try :
citiesFC = arcpy.GetParameterAsText(1) # cities Layer is cities Feature Layer
crimefieldindex = arcpy.GetParameterAsText(2) # crime index is CRIME_INDE and is a Double integer
whereClause1 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, crimeField), crimefieldindex)
crimeField = arcpy.GetParameterAsText(3) # crimeField is fieldname 'CRIME_INDE' SQL expression
universityfieldindex = arcpy.GetParameterAsText(4) # universityfieldindex is the UNIVERSITY field and is DOUBLE integer
whereClause2 = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(citiesL, universityField), universityfieldindex)
universityField = arcpy.GetParameterAsText(5) # universityField is fieldname 'UNIVERSITY' SQL expression
outputlayer = arcpy.GetParameterAsText(6) # output layer name
# make a layer from the cities feature class
arcpy.MakeFeatureLayer_management(citiesFC, "citiesL")
# select the attributes from citiesL from user input
prj = ""
prj2 = ""
if prj.find("CRIME_INDE")>=0:
crimecount = 1
print 'using crime index'
elif prj2.find("UNIVERSITY")>=1:
unicount = 2
print 'using university status'
# set field to determine where clause variables 1=crime 2=university 3=crime and university else: none selected
usecityfield = crimecount + unicount
if usecityfield == 1:
arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", crimefieldindex)
arcpy.CopyFeatures_management("citiesL", "citycrime")
elif usecityfield == 2:
arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", universityfieldindex)
arcpy.CopyFeatures_management("citiesL", "cityuni")
elif usecityfield == 3:
arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", crimefieldindex + universityfieldindex)
arcpy.CopyFeatures_management("citiesL", "citycrimeuni")
else:
# write selected features to a new featureclass
arcpy.CopyFeatures_management("citiesL", "SUBSET_SELECTION")
except:
print arcpy.GetMessages()
... View more
04-08-2013
05:08 AM
|
0
|
3
|
965
|
|
POST
|
Thanks Chris for your quick reply. I put quotes around "CITYNAME" but the field still does not update with the NAME field. The edited code is shown below and I wondered if you had any other ideas? Thanks again Scott
# ExtractFeaturesByLocationAndAttribute.py EFLA.py
# Description: Extract features to a new feature class based on a Location and an attribute query
# then add field called CITYNAME and update it with the NAME field from the cities layer
# import system modules
import arcpy
from arcpy import env
import os
# set overwrite option
arcpy.env.overwriteOutput = True
# Put in error trapping in case an error occurs when running tool
try:
# Make a layer from the cities feature class
arcpy.MakeFeatureLayer_management("H:/working/Findsites.gdb/cities","citiesL")
# Select all cities that are within 30km of an interstate
arcpy.SelectLayerByLocation_management("citiesL", "WITHIN_A_DISTANCE", "H:/working/Findsites.gdb/interstates", "30 KILOMETERS", "NEW_SELECTION")
# Within the selection (done above) further select only those cities that have a university and low crime rate
arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", "UNIVERSITY = 1 AND CRIME_INDE <= 0.02")
# Make a layer from the counties feature class
arcpy.MakeFeatureLayer_management("H://working/Findsites.gdb/counties","countiesL")
# From the counties layer select only those counties with a large enough workforce and number of farms
arcpy.SelectLayerByAttribute_management("countiesL", "NEW_SELECTION", "AGE_18_64 >= 25000 AND NO_FARMS87 >= 500")
# Select all cities that intersect counties that meet work force and number of farms criteria
arcpy.SelectLayerByLocation_management("citiesL", "INTERSECT", "countiesL", "", "SUBSET_SELECTION")
# Write the selected features to a new featureclass
arcpy.CopyFeatures_management("citiesL", "H:/working/Findsites.gdb/CityList")
# create a new field called CITYNAME to replace NAME because other datasets have a NAME field
arcpy.AddField_management("H:/working/Findsites.gdb/CityList", "CITYNAME", "TEXT", "", "", "25")
expression1 = '!NAME!'
arcpy.CalculateField_management(CityList, "CITYNAME", expression1, "PYTHON")
except:
# If an error occurred print the message to the screen
print arcpy.GetMessages()
... View more
04-04-2013
12:14 PM
|
0
|
0
|
821
|
|
POST
|
Thanks Chris for your quick reply. I changed CityList to "CityList" (code below) but it still doesn't update the new CITYNAME field with the NAME field. Do you perhaps have any other suggestions?
# ExtractFeaturesByLocationAndAttribute.py EFLA.py
# Description: Extract features to a new feature class based on a Location and an attribute query
# then add field called CITYNAME and update it with the NAME field from the cities layer
# import system modules
import arcpy
from arcpy import env
import os
# set overwrite option
arcpy.env.overwriteOutput = True
# Put in error trapping in case an error occurs when running tool
try:
# Make a layer from the cities feature class
arcpy.MakeFeatureLayer_management("H:/working/Findsites.gdb/cities","citiesL")
# Select all cities that are within 30km of an interstate
arcpy.SelectLayerByLocation_management("citiesL", "WITHIN_A_DISTANCE", "H:/working/Findsites.gdb/interstates", "30 KILOMETERS", "NEW_SELECTION")
# Within the selection (done above) further select only those cities that have a university and low crime rate
arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", "UNIVERSITY = 1 AND CRIME_INDE <= 0.02")
# Make a layer from the counties feature class
arcpy.MakeFeatureLayer_management("H://working/Findsites.gdb/counties","countiesL")
# From the counties layer select only those counties with a large enough workforce and number of farms
arcpy.SelectLayerByAttribute_management("countiesL", "NEW_SELECTION", "AGE_18_64 >= 25000 AND NO_FARMS87 >= 500")
# Select all cities that intersect counties that meet work force and number of farms criteria
arcpy.SelectLayerByLocation_management("citiesL", "INTERSECT", "countiesL", "", "SUBSET_SELECTION")
# Write the selected features to a new featureclass
arcpy.CopyFeatures_management("citiesL", "H:/working/Findsites.gdb/CityList")
# create a new field called CITYNAME to replace NAME because other datasets have a NAME field
arcpy.AddField_management("H:/working/Findsites.gdb/CityList", "CITYNAME", "TEXT", "", "", "25")
expression1 = '!NAME!'
arcpy.CalculateField_management(CityList, "CITYNAME", expression1, "PYTHON")
except:
# If an error occurred print the message to the screen
print arcpy.GetMessages()
... View more
04-04-2013
12:07 PM
|
0
|
0
|
821
|
|
POST
|
Hi, I've written a script that narrows down a selection of points (cities) and then adds a field called CITYNAME to the feature class. I need to update the new CITYNAME field with the same values as the NAME field in the same feature class but it doesn't update them although it shows as having run successfully. I need to do this so that I can spatially join this points (cities) dataset to polygons (counties) and lines (roads) because all three of them have the same fieldname called NAME. I'm using ArcGIS v10.0 and any help would be appreciated as I've tried various methods like CalculateField and UpdateCursor to no avail. Thanks, Scotaidh
# ExtractFeaturesByLocationAndAttribute.py EFLA.py
# Description: Extract features to a new feature class based on a Location and an attribute query
# then add field called CITYNAME and update it with the NAME field from the cities layer
# import system modules
import arcpy
from arcpy import env
import os
# set overwrite option
arcpy.env.overwriteOutput = True
# Put in error trapping in case an error occurs when running tool
try:
# Make a layer from the cities feature class
arcpy.MakeFeatureLayer_management("H:/working/Findsites.gdb/cities","citiesL")
# Select all cities that are within 30km of an interstate
arcpy.SelectLayerByLocation_management("citiesL", "WITHIN_A_DISTANCE", "H:/working/Findsites.gdb/interstates", "30 KILOMETERS", "NEW_SELECTION")
# Within the selection (done above) further select only those cities that have a university and low crime rate
arcpy.SelectLayerByAttribute_management("citiesL", "SUBSET_SELECTION", "UNIVERSITY = 1 AND CRIME_INDE <= 0.02")
# Make a layer from the counties feature class
arcpy.MakeFeatureLayer_management("H://working/Findsites.gdb/counties","countiesL")
# From the counties layer select only those counties with a large enough workforce and number of farms
arcpy.SelectLayerByAttribute_management("countiesL", "NEW_SELECTION", "AGE_18_64 >= 25000 AND NO_FARMS87 >= 500")
# Select all cities that intersect counties that meet work force and number of farms criteria
arcpy.SelectLayerByLocation_management("citiesL", "INTERSECT", "countiesL", "", "SUBSET_SELECTION")
# Write the selected features to a new featureclass
arcpy.CopyFeatures_management("citiesL", "H:/working/Findsites.gdb/CityList")
# create a new field called CITYNAME to replace NAME because other datasets have a NAME field
arcpy.AddField_management("H:/working/Findsites.gdb/CityList", "CITYNAME", "TEXT", "", "", "25")
expression1 = '!MP_VAL!'
arcpy.CalculateField_management(CityList, CITYNAME, expression1, "PYTHON", "")
#Calculate Field - update new CITYNAME field with NAME field
# arcpy.AddMessage("Calculating Updated Field...")
# Expression = "'{0}'".format(arcpy.GetValue(NAME))
# single quoted string literal
# arcpy.CalculateField_management(CityList, CITYNAME, Expression, "PYTHON")
except:
# If an error occurred print the message to the screen
print arcpy.GetMessages()
... View more
04-04-2013
09:06 AM
|
0
|
5
|
1359
|
|
POST
|
PLEASE HELP URGENT - Is there anyone at all who can help with this? I wrote a script based on the Extract Value To Points tool but it doesn't work properly. I have a simplified line shapefile and I want to add elevation (z values) from a DEM raster layer to the end points of the lines. I have written the following code (its user input) but when I run it as a tool it reports that it has run successfully but it doesn't actually output the point shape file with the z values! Any hints or even alternative suggestions would be appreciated. code - # script to extract raster values to point shapefile # adapted by Scott MacDonald Kingston University k0848626 GSM655Programming Asssignment C # import system modules import arcpy from arcpy import env from arcpy.sa import * # get user supplied path, layers and fields path = arcpy.GetParameterAsText(0) arcpy.env.workspace = path # in Feature Layer is Confluence_Pts in_point_features = arcpy.GetParameterAsText(1) # in Raster Layer is DEM in_raster = arcpy.GetParameterAsText(2) # out Feature Class out_point_features = arcpy.GetParameterAsText(3) # error trapping measures try: # check out spatial analyst extension arcpy.CheckOutExtension("Spatial") # run the ExractValuesToPoints tool arcpy.ExtractValuesToPoints(in_point_features, in_raster, out_point_features) # check in spatial analyst extension arcpy.CheckInExtension("Spatial") except: print arcpy.GetMessages()
... View more
01-09-2013
10:43 AM
|
0
|
2
|
2365
|
|
POST
|
Perfect - it's working fine now, thanks a lot for your help
... View more
01-09-2013
07:53 AM
|
0
|
0
|
1613
|
|
POST
|
Thanks again Matthew for your reply. Unfortunately I'm still having problems. Firstly, I removed the 'path is workspace' line but it made no difference. I decided to try your Select_analysis suggestion but I can't seem to get the Where_clause running correctly. I get the following error message - <type 'exceptions.NameError'>: name 'typeField' is not defined Failed to execute (Select). I'd be grateful for any advice on this as I've been trying to create this layer for days now to no avail! Scott code - # extract features by select analysis # import system modules import arcpy # get user supplied path, layers and fields path = arcpy.GetParameterAsText(0) arcpy.env.workspace = path # riverLayer is Rio_Panuco_Lyr Feature Layer inputLayer = arcpy.GetParameterAsText(1) # confluence is river type 'link' and is a string confluence = arcpy.GetParameterAsText(2) whereClause = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(inputLayer, typeField), confluence) # typeField is fieldname 'type' and is SQL expression typeField = arcpy.GetParameterAsText(3) # set output location outputLayer = arcpy.GetParameterAsText(4) # error trapping measures try: # make a layer from the feature class arcpy.Select_analysis(inputLayer, outputLayer, whereClause) except: print arcpy.GetMessages()
... View more
01-08-2013
12:38 PM
|
0
|
0
|
1613
|
|
POST
|
Thanks mzcoyle for replying to my thread. I tried substituting some of my code for the code that you sent (script below) but I couldn't get it to work. It came up with the following error - <type 'exceptions.NameError'>: name 'path' is not defined Failed to execute (tryRiver). I am also not sure why I was using a cursor - I thought I needed this to search through the fieldname (called type) for rivertypes (called link). I'm new to scripting and all I want to do is create an Arc tool based on arcpy scripting that lets a user navigate to the feature class (Rio_Panuco) and lets them select "type" = 'link' (fieldname = attribute) and saves the feature to a new layer. I've noticed that the select by attributes tool required a layer as input and not a dataset so I couldn't get that to work and I tried basic make feature layer commands. I can make a feature layer from a feature class using user input but I cannot select only fields whose type = link and then save it to a new layer. I would appreciate any further help or suggestions on this. Code was - # extract features by attrtibute # import system modules import arcpy from arcpy import env # get user supplied path, layers and fields path is workspace path = arcpy.GetParameterAsText(0) # riverLayer is Rio_Panuco_Lyr Feature Layer inputLayer = arcpy.GetParameterAsText(1) # confluence is river type 'link' and is a string confluence = arcpy.GetParameterAsText(2) whereClause = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(inputLayer, typeField), confluence) # typeField is fieldname 'type' and is SQL expression typeField = arcpy.GetParameterAsText(3) # set output location outputLayer = arcpy.GetParameterAsText() # set overwrite option # arcp.overwriteOutput = true # error trapping measures try: # make a layer from the feature class arcpy.MakeFeatureLayer_management(inputLayer, "River_lyr") # select layer by attribute arcpy.SelectLayerByAttribute_management("River_lyr", "SelectionRiverLayer", whereClause) # write selected features to a new featureclass arcpy.CopyFeatures_management("River_lyr", "SelectionRiverLayer") except: print arcpy.GetMessages() Kind regards Scottaidh
... View more
01-08-2013
09:04 AM
|
0
|
0
|
1613
|
|
POST
|
I have been puzzling over a script I have to write and run in an Arc toolbox and I wondered if anyone could tell me where I'm going wrong. The following code relates to a rivers shapefile called Rio_Panuco in a geodatabase called panuco.gdb. There is a field in the shape file called "type" and the attribute I want to select is "link". I was able to create the file I wanted when the script was hard coded to the geodatabase using the code below- arcpy.SelectLayerByAttribute_management("River_lyr", "NEW_SELECTION", '"type" = \'link\'') However, I need to write generic code and require the user to input the requirements i.e. Select * from Rio_Panuco where "type" = 'link' I have written the following code to do this (and variations galore!) but still cannot get it to work properly. I've also put the code in ArcToolbox but when the Select Layer By Attribute box is clicked it is blank. I would be grateful for any advice. # extract features by attrtibute # import system modules import arcpy from arcpy import env # get user supplied path, layers and fields path is workspace path = arcpy.GetParameterAsText(0) # riverLayer is Rio_Panuco_Lyr Feature Layer inputLayer = arcpy.GetParameterAsText(1) # confluence is river type 'link' and is a string confluence = arcpy.GetParameterAsText(2) whereClause = '"' str(typeField) + " = '" + str(confluence) + "'" rows = arcpy.SearchCursor(inputLayer, whereClause) # typeField is fieldname 'type' and is SQL expression typeField = arcpy.GetParameterAsText(3) # set output location outputLayer = arcpy.GetParameterAsText() # set overwrite option # arcp.overwriteOutput = true # error trapping measures try: # make a layer from the feature class arcpy.MakeFeatureLayer_management(inputLayer, "River_lyr") # select layer by attribute arcpy.SelectLayerByAttribute_management("River_lyr", "SelectionRiverLayer", whereClause) # write selected features to a new featureclass arcpy.CopyFeatures_management("River_lyr", "SelectionRiverLayer") except: print arcpy.GetMessages()
... View more
01-08-2013
07:15 AM
|
0
|
6
|
2990
|
|
POST
|
Thanks again Michael - I'll give that a go and post a reply
... View more
10-15-2012
08:01 AM
|
0
|
0
|
6103
|
|
POST
|
Hi Michael Thanks for the post you sent regarding my query - it was definately the best explanation yet and it worked! The only downside is that the coordinates are all about 30 metres out from where they should be - although the route is correct! I've attached a file to illustrate this as the points should really be positioned on the road and path network. Do you know if there's a way to improve the accuracy of the points? Thanks again though - much appreciated, Scott
... View more
10-15-2012
07:27 AM
|
0
|
0
|
6103
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 06-22-2017 01:24 AM |
| Online Status |
Offline
|
| Date Last Visited |
11-11-2020
02:23 AM
|