Quantcast
Channel: Forums - Python
Viewing all 2485 articles
Browse latest View live

Calculate Field management throwing field name error

$
0
0
I have been racking my brain for over a week now and no matter how I format my code, the arcpy.CalculateField_management line just will not run for me.

The parts of the code for the operation are below.

Code:

arcpy.env.overwriteOutput = True
env.workspce = "F:/GIS Data/Drivetesting.gdb"
#mxd = arcpy.mapping.MapDocument("CURRENT") --used in the Arcpy environment
#df = arcpy.mapping.ListDataFrames(mxd, "New Data Frame")  --used in the Arcpy environment
Field = "PCode1"
FC = "F:/GIS Data/Drivetesting.gdb/Carrier/Phone"
MyField = Myfield = arcpy.ListFields(FC)[24]
arcpy.MakeFeatureLayer_management(FC,"FC_lyr")
---------> tons of geoprocessing going on right here, but not included as not relevant to question (and saves space!)
    mylist = []
    # Iterate through the rows in the cursor

    for item in Scursor:
        a = (item.Frequency, item.PCode1,)
        mylist.append(a)
       
    mylist.sort()
    mylist.reverse()
    del mylist[1:]
    applist = [x[1] for x in mylist]
    applist.append(CellIDs.UNIQUE_ID)
    applist.append(CellIDs.CellID)
    print applist
    PCode1 = str(applist[0])
    PCode2 = str(applist[1])
    PCode3 = str(applist[2])
    Unitname = str(applist[3])
    Columnname = '"Cellname1"'
    print Cellname
    print MyField.name
   
    arcpy.SelectLayerByAttribute_management("FC_lyr","SUBSET_SELECTION",' "PN1" = ' + PCode1 + " or \"PN1\" = " + PCode2 + " or \"PN1\" = " + PCode3)
    arcpy.CalculateField_management("FC_lyr",Columnname,Unitname)

It throws

Code:

ERROR 000728: Field "Cellname1" does not exist within table
Failed to execute (CalculateField).

I've tried writing out Cellname1, I've tried getting it through arcpy.listfields. I've tried single quotes, double quotes, quoting the quotes...you name it; I think I've tried it. If anyone has any idea why this is happening, I would greatly appreciate some assistance as I am at my wits end here. I know the field name exists as the 'print MyField.name' is derived from the listfields function, and gives me "Cellname1" as my result. PLEASE HELP!

Where Clause SQL syntax problem - Urgent Please Help

$
0
0
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

[CODE]
# 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}

SQL where clause problem - Grateful for help. Please Help

$
0
0
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
[CODE]
# 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]

Export Page Layout to PNG, type 'exceptions.AssertionError'

$
0
0
I'm using ArcGIS 10.0 sp5 on a Win7 PC and need help with a script to turn layers on/off and export the page layout to an image file. The script works until the ExportToPNG(). I have 281 layers with up to 10 attributes I have to map (static extent) so scripting the arduous task of changing each layers visibility is preferred. I have a VBA tool to change the symbology between the 10 attributes of selected layers and now I'd like to take advantage of the arcpy.mapping functionalities.

Code:

import os, sys, string, arcpy

# define list of species
spLst = ['0070','1320']

try:
    mxd = arcpy.mapping.MapDocument(r"C:/Workspace/Species.mxd")

    # check for broken paths
    brknList = arcpy.mapping.ListBrokenDataSources(mxd)
    if len(brknList) >= 1:
        print "Broken Paths Exist..." + brknList
    else:
        for sp in spLst:
            print "No broken paths, proceeding"
            lyrName = "ew20km_in" + str(sp) + "_2040"
           
            lyrList = arcpy.mapping.ListLayers(mxd, lyrName)
           
            for lyr in lyrList:
               
                # define variables
                out_png1 = r"C:/Workspace/pixels_500/rfbird_" + str(sp) + "_2040.png"
                out_png2 = r"C:/Workspace/pixels_800/rfbird_" + str(sp) + "_2040.png"
                resolution1 = 45 
                resolution2 = 72
               
                lyr.visible = True # make layer visible, all other species should start as invisible
               
                arcpy.RefreshTOC()
                arcpy.RefreshActiveView()
               
                # export current layout view to png file
                # ExportToPNG (map_document, out_png, {data_frame}, {df_export_width}, {df_export_height}, {resolution}, {world_file}, {color_mode}, {background_color}, {transparent_color}, {interlaced})
               
                arcpy.mapping.ExportToPNG(mxd, out_png1, "PAGE_LAYOUT", "", "", resolution1, "", "24-BIT_TRUE_COLOR", "", "", "")
                arcpy.mapping.ExportToPNG(mxd, out_png2, "PAGE_LAYOUT", "", "", resolution2, "", "24-BIT_TRUE_COLOR", "", "", "")
               
                lyr.visible = False

except:
    arcpy.AddMessage(arcpy.GetMessages(2))
    print arcpy.GetMessages (2)
    print "Exited with Errors.... Something is wrong"

Export to shapefile (multiple) command?

$
0
0
Can someone please tell me, is there an arcpy command to export to shapefile (multiple) as you would do in ArcCatalog?

Thanks

SQL where caluse syntax Please Help

$
0
0
Not sure if I have to post again but older things just seem to get ignored.

Please can someone tell me how to write the where clause for

"CRIME_INDE" <= 0.02 AND "UNIVERSITY" = 1

when everthing is a variable.

I have posted my code below. Please ignore the other lines, they all work. The workspaces, paths etc. are user input and are not shown, dont worry - they work. You'll notice several lines of code for the whereclause preceded by # thats because I've tried them and they dont' work. The ONLY part that does not work is the where clauses for SelectLayerByAttribute.

Any suggestions are greatly appreciated so please help.

Scottaidh

[CODE]
# 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"
counties = arcpy.GetParameterAsText(2) # counties Layer is counties Feature Layer counties.shp
countiesL ="countiesL"
interstates = arcpy.GetParameterAsText(3) # interstates Layer is Feature Layer interstates.shp
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 = '"' + crimeField + '" <= " + crimefieldindex'
#whereClause = '"' + crimeField + '" <= ' + "'" + crimefieldindex + "'"
whereClause = "\"%s\" = '%s'" % (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 = "'"' + universityField + '" <=' + universityindex"
#whereClause2 = '"' + universityField + '" <= ' + "'" + universityfieldindex + "'"
whereClause2 = "\"%s\" = '%s'" % (universityField, universityfieldindex)
workforceField = arcpy.GetParameterAsText(8) # workforceField is fieldname 'AGE_18_64' SQL expression
workforceindex = arcpy.GetParameterAsText(9) # workforce index is attribute of AGE_18_64 field and is a Double and is 25000
#whereClause3 = "'"' + workforceField + '" >=' + workforceindex"
#whereClause3 = '"' + workforceField + '" >= ' + "'" + workforceindex + "'"
whereClause3 = "\"%s\" = '%s'" % (workforceField, workforceindex)
farmField = arcpy.GetParameterAsText(10) # farmField is fieldname 'NO_FARMS87' SQL expression
farmfieldindex = arcpy.GetParameterAsText(11) # farmfieldindex is the NO_FARMS87 field and is Double integer is 500
#whereClause4 = "'"' +farmField + '" >=' + farmfieldindex"
#whereClause4 = '"' + farmField + '" >= ' + "'" + farmfieldindex + "'"
whereClause = "\"%s\" = '%s'" % (farmField, farmfieldindex)
maxKmInterstate = arcpy.GetParameterAsText(12) # interstate WITHIN_A_DISTANCE linear unit
nearestInterstate = arcpy.GetParameterAsText(13) # Near Table Analysis table generated
targetFeatures = "cityListL" # cities spatial join layer
joinFeatures = "countiesL" # counties spatial join layer
cityListFC = arcpy.GetParameterAsText(14) # narrowed down cities list temporary
cityListL = "CityListL" # the feature layer of the generated cityList feature class
outputLayer = arcpy.GetParameterAsText(15) # ootput

#altwhereclause1 = "CRIME_INDE <= 0.02"
#altwhereclause2 = "UNIVERSITY = 1"
#altwhereclause3 = "AGE_18_64 >= 25000"
#altwhereclause4 = "NO_FARMS87 = 500"


# 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, maxKmInterstate, "NEW_SELECTION")

# Here is the ESRi suggested code for select layer by attribute where clause - doesn't work though
# whereClause = '"' + crimeField + '" <=' + "'" + crimefieldindex + "'"
# arcpy.SelectLayerByAttribute_management(citiesL, "NEW_SELECTION", whereClause + "AND" + whereClause2)
# stack exchange suggestion - whereClause = '"' + PipelineIDField + '" = ' + "'" + fullRouteName + "'"

# from selection above select layer by attribute select "CRIME_IND" <= 0.02 AND "UNIVERSITY" = 1
arcpy.SelectLayerByAttribute_management(citiesL, "NEW_SELECTION", whereClause + "AND" + whereClause2)

# 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 + "AND" + whereClause4)

# from selection above select cities intersecting counties
arcpy.SelectLayerByLocation_management(citiesL, "INTERSECT", countiesL, "", "SUBSET_SELECTION")

# save selected features
# arcpy.CopyFeatures_management(citiesL, cityListFC)

# arcpy.Select_analysis(citiesL, cityListFC, "")
arcpy.FeatureClassToShapefile_conversion(citiesL, path)

# make temp cities list feature layer so that the output can be spatially joined to counties
# arcpy.MakeFeatureLayer_management(cityListFC,cityListL)

#arcpy.AddField_management(citiesL, "CITYNAME", "TEXT", "", "", "25")
#arcpy.AddField_management(citiesL, "CRIMEINDX", "DOUBLE", "", "", "")
#arcpy.AddField_management(citiesL, "HAS_UNI", "TEXT", "", "", "3")
#arcpy.CalculateField_management(citiesL, "CITYNAME", "!NAME!", "PYTHON")
#arcpy.CalculateField_management(citiesL, "CRIMEINDX", "!CRIME_INDE!", "PYTHON")
#arcpy.CalculateField_management(citiesL, "HAS_UNI", "!UNIVERSITY!", "PYTHON")
#arcpy.DeleteField_management(citiesL,["NAME", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["CRIME_INDE", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["UNIVERSITY", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["ID", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["POPULATION", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["TOTAL_CRIM", "LABEL", "CLASS"])

# Generate NearTable_analysis to find closest interstate distance
arcpy.GenerateNearTable_analysis(citiesL, interstates, nearestInterstate, maxKmInterstate)

# join new city list layer to generated Near Table
arcpy.AddJoin_management(citiesL, "NEAR_FID", nearestInterstate, "IN_FID")

# Run the Spatial Join tool, using the defaults for the join operation and join type
arcpy.SpatialJoin_analysis(targetFeatures, joinFeatures, outputLayer, "#", "#", "#")





print arcpy.GetMessages()
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)

# save selected features FINAL OOTPUT here
# arcpy.CopyFeatures_management(citiesL, outputLayer)

print arcpy.GetMessages()
[\CODE]

arcpy.da cursors and layer definition query

$
0
0
In my mxd I found that if I ran an arcpy.da search cursor with a where clause on a layer that had a definition query applied to it, that the where clause would not be honored. Anybody else have this problem?

Thanks
George

Which sides of a parcel have road frontage.

$
0
0
Im trying to figure out how to find which 'side' of a land parcel has road frontage. The matter is complicated by our PA not storing true curves when they draw the parcels. Any cul-de-sac is made of hundreds of tiny lines each technically a side of the polygon. Ive converted polygons to lines and split at vertex but I cant figure out of the line fronts a road. I was thinking that if I can flag the segments as road front I could delete the other lines and merger the remaining back into longer lines by parcel ID. Any ideas on how to check this?

I need some help with os.walk and defining shapefiles in sub folders

$
0
0
So far this is what I have. It works if the shapefiles are in the C:/test_define folder, but it will fail with this error if they are in sub
folders. I am new to this so I am probably missing something simple, but I can't figure it out..

2000-10-Straight hole well.shp
--------------------------------------------------
Failed to execute. Parameters are not valid.
ERROR 000732: Input Dataset or Feature Class: Dataset 2000-10-Straight hole well.shp does not exist or is not supported
Failed to execute (DefineProjection).

My code
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import os
import arcpy

# Set workspace environment to a folder
WS = "c:/test_define"
arcpy.env.workspace = WS

for (path, dirs, files) in os.walk(WS):
for name in files:
if name.endswith(".shp"):
print name
print ("-") * 50
try:
infc = name
sr = arcpy.SpatialReference("NAD 1983 UTM Zone 11N")
arcpy.DefineProjection_management(infc, sr)

# print messages when the tool runs successfully
print(arcpy.GetMessages(0))

except arcpy.ExecuteError:
print(arcpy.GetMessages(2))

except Exception as ex:
print(ex.args[0])

Creating a Add-IN to select a feature in a feature class and displaying results.

$
0
0
I was wondering the solution would be to have button click, enable selection on a feature class (predefined) and reurning the attiributes. So you have turn select button on and off that is on arcmap. Can you do this or do you have the user already be in delect mode which defeats the purpose? I am new at python add ins so trying figure out syntax. This is just like the information button but I need to format the output.

Calculate Field management throwing field name error

$
0
0
I have been racking my brain for over a week now and no matter how I format my code, the arcpy.CalculateField_management line just will not run for me.

The parts of the code for the operation are below.

Code:

arcpy.env.overwriteOutput = True
env.workspce = "F:/GIS Data/Drivetesting.gdb"
#mxd = arcpy.mapping.MapDocument("CURRENT") --used in the Arcpy environment
#df = arcpy.mapping.ListDataFrames(mxd, "New Data Frame")  --used in the Arcpy environment
Field = "PCode1"
FC = "F:/GIS Data/Drivetesting.gdb/Carrier/Phone"
MyField = Myfield = arcpy.ListFields(FC)[24]
arcpy.MakeFeatureLayer_management(FC,"FC_lyr")
---------> tons of geoprocessing going on right here, but not included as not relevant to question (and saves space!)
    mylist = []
    # Iterate through the rows in the cursor

    for item in Scursor:
        a = (item.Frequency, item.PCode1,)
        mylist.append(a)
       
    mylist.sort()
    mylist.reverse()
    del mylist[1:]
    applist = [x[1] for x in mylist]
    applist.append(CellIDs.UNIQUE_ID)
    applist.append(CellIDs.CellID)
    print applist
    PCode1 = str(applist[0])
    PCode2 = str(applist[1])
    PCode3 = str(applist[2])
    Unitname = str(applist[3])
    Columnname = '"Cellname1"'
    print Cellname
    print MyField.name
   
    arcpy.SelectLayerByAttribute_management("FC_lyr","SUBSET_SELECTION",' "PN1" = ' + PCode1 + " or \"PN1\" = " + PCode2 + " or \"PN1\" = " + PCode3)
    arcpy.CalculateField_management("FC_lyr",Columnname,Unitname)

It throws

Code:

ERROR 000728: Field "Cellname1" does not exist within table
Failed to execute (CalculateField).

I've tried writing out Cellname1, I've tried getting it through arcpy.listfields. I've tried single quotes, double quotes, quoting the quotes...you name it; I think I've tried it. If anyone has any idea why this is happening, I would greatly appreciate some assistance as I am at my wits end here. I know the field name exists as the 'print MyField.name' is derived from the listfields function, and gives me "Cellname1" as my result. PLEASE HELP!

Where Clause SQL syntax problem - Urgent Please Help

$
0
0
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

[CODE]
# 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}

SQL where clause problem - Grateful for help. Please Help

$
0
0
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
[CODE]
# 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]

Export Page Layout to PNG, type 'exceptions.AssertionError'

$
0
0
I'm using ArcGIS 10.0 sp5 on a Win7 PC and need help with a script to turn layers on/off and export the page layout to an image file. The script works until the ExportToPNG(). I have 281 layers with up to 10 attributes I have to map (static extent) so scripting the arduous task of changing each layers visibility is preferred. I have a VBA tool to change the symbology between the 10 attributes of selected layers and now I'd like to take advantage of the arcpy.mapping functionalities.

Code:

import os, sys, string, arcpy

# define list of species
spLst = ['0070','1320']

try:
    mxd = arcpy.mapping.MapDocument(r"C:/Workspace/Species.mxd")

    # check for broken paths
    brknList = arcpy.mapping.ListBrokenDataSources(mxd)
    if len(brknList) >= 1:
        print "Broken Paths Exist..." + brknList
    else:
        for sp in spLst:
            print "No broken paths, proceeding"
            lyrName = "ew20km_in" + str(sp) + "_2040"
           
            lyrList = arcpy.mapping.ListLayers(mxd, lyrName)
           
            for lyr in lyrList:
               
                # define variables
                out_png1 = r"C:/Workspace/pixels_500/rfbird_" + str(sp) + "_2040.png"
                out_png2 = r"C:/Workspace/pixels_800/rfbird_" + str(sp) + "_2040.png"
                resolution1 = 45 
                resolution2 = 72
               
                lyr.visible = True # make layer visible, all other species should start as invisible
               
                arcpy.RefreshTOC()
                arcpy.RefreshActiveView()
               
                # export current layout view to png file
                # ExportToPNG (map_document, out_png, {data_frame}, {df_export_width}, {df_export_height}, {resolution}, {world_file}, {color_mode}, {background_color}, {transparent_color}, {interlaced})
               
                arcpy.mapping.ExportToPNG(mxd, out_png1, "PAGE_LAYOUT", "", "", resolution1, "", "24-BIT_TRUE_COLOR", "", "", "")
                arcpy.mapping.ExportToPNG(mxd, out_png2, "PAGE_LAYOUT", "", "", resolution2, "", "24-BIT_TRUE_COLOR", "", "", "")
               
                lyr.visible = False

except:
    arcpy.AddMessage(arcpy.GetMessages(2))
    print arcpy.GetMessages (2)
    print "Exited with Errors.... Something is wrong"

Export to shapefile (multiple) command?

$
0
0
Can someone please tell me, is there an arcpy command to export to shapefile (multiple) as you would do in ArcCatalog?

Thanks

SQL where caluse syntax Please Help

$
0
0
Not sure if I have to post again but older things just seem to get ignored.

Please can someone tell me how to write the where clause for

"CRIME_INDE" <= 0.02 AND "UNIVERSITY" = 1

when everthing is a variable.

I have posted my code below. Please ignore the other lines, they all work. The workspaces, paths etc. are user input and are not shown, dont worry - they work. You'll notice several lines of code for the whereclause preceded by # thats because I've tried them and they dont' work. The ONLY part that does not work is the where clauses for SelectLayerByAttribute.

Any suggestions are greatly appreciated so please help.

Scottaidh

[CODE]
# 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"
counties = arcpy.GetParameterAsText(2) # counties Layer is counties Feature Layer counties.shp
countiesL ="countiesL"
interstates = arcpy.GetParameterAsText(3) # interstates Layer is Feature Layer interstates.shp
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 = '"' + crimeField + '" <= " + crimefieldindex'
#whereClause = '"' + crimeField + '" <= ' + "'" + crimefieldindex + "'"
whereClause = "\"%s\" = '%s'" % (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 = "'"' + universityField + '" <=' + universityindex"
#whereClause2 = '"' + universityField + '" <= ' + "'" + universityfieldindex + "'"
whereClause2 = "\"%s\" = '%s'" % (universityField, universityfieldindex)
workforceField = arcpy.GetParameterAsText(8) # workforceField is fieldname 'AGE_18_64' SQL expression
workforceindex = arcpy.GetParameterAsText(9) # workforce index is attribute of AGE_18_64 field and is a Double and is 25000
#whereClause3 = "'"' + workforceField + '" >=' + workforceindex"
#whereClause3 = '"' + workforceField + '" >= ' + "'" + workforceindex + "'"
whereClause3 = "\"%s\" = '%s'" % (workforceField, workforceindex)
farmField = arcpy.GetParameterAsText(10) # farmField is fieldname 'NO_FARMS87' SQL expression
farmfieldindex = arcpy.GetParameterAsText(11) # farmfieldindex is the NO_FARMS87 field and is Double integer is 500
#whereClause4 = "'"' +farmField + '" >=' + farmfieldindex"
#whereClause4 = '"' + farmField + '" >= ' + "'" + farmfieldindex + "'"
whereClause = "\"%s\" = '%s'" % (farmField, farmfieldindex)
maxKmInterstate = arcpy.GetParameterAsText(12) # interstate WITHIN_A_DISTANCE linear unit
nearestInterstate = arcpy.GetParameterAsText(13) # Near Table Analysis table generated
targetFeatures = "cityListL" # cities spatial join layer
joinFeatures = "countiesL" # counties spatial join layer
cityListFC = arcpy.GetParameterAsText(14) # narrowed down cities list temporary
cityListL = "CityListL" # the feature layer of the generated cityList feature class
outputLayer = arcpy.GetParameterAsText(15) # ootput

#altwhereclause1 = "CRIME_INDE <= 0.02"
#altwhereclause2 = "UNIVERSITY = 1"
#altwhereclause3 = "AGE_18_64 >= 25000"
#altwhereclause4 = "NO_FARMS87 = 500"


# 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, maxKmInterstate, "NEW_SELECTION")

# Here is the ESRi suggested code for select layer by attribute where clause - doesn't work though
# whereClause = '"' + crimeField + '" <=' + "'" + crimefieldindex + "'"
# arcpy.SelectLayerByAttribute_management(citiesL, "NEW_SELECTION", whereClause + "AND" + whereClause2)
# stack exchange suggestion - whereClause = '"' + PipelineIDField + '" = ' + "'" + fullRouteName + "'"

# from selection above select layer by attribute select "CRIME_IND" <= 0.02 AND "UNIVERSITY" = 1
arcpy.SelectLayerByAttribute_management(citiesL, "NEW_SELECTION", whereClause + "AND" + whereClause2)

# 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 + "AND" + whereClause4)

# from selection above select cities intersecting counties
arcpy.SelectLayerByLocation_management(citiesL, "INTERSECT", countiesL, "", "SUBSET_SELECTION")

# save selected features
# arcpy.CopyFeatures_management(citiesL, cityListFC)

# arcpy.Select_analysis(citiesL, cityListFC, "")
arcpy.FeatureClassToShapefile_conversion(citiesL, path)

# make temp cities list feature layer so that the output can be spatially joined to counties
# arcpy.MakeFeatureLayer_management(cityListFC,cityListL)

#arcpy.AddField_management(citiesL, "CITYNAME", "TEXT", "", "", "25")
#arcpy.AddField_management(citiesL, "CRIMEINDX", "DOUBLE", "", "", "")
#arcpy.AddField_management(citiesL, "HAS_UNI", "TEXT", "", "", "3")
#arcpy.CalculateField_management(citiesL, "CITYNAME", "!NAME!", "PYTHON")
#arcpy.CalculateField_management(citiesL, "CRIMEINDX", "!CRIME_INDE!", "PYTHON")
#arcpy.CalculateField_management(citiesL, "HAS_UNI", "!UNIVERSITY!", "PYTHON")
#arcpy.DeleteField_management(citiesL,["NAME", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["CRIME_INDE", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["UNIVERSITY", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["ID", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["POPULATION", "LABEL", "CLASS"])
#arcpy.DeleteField_management(citiesL,["TOTAL_CRIM", "LABEL", "CLASS"])

# Generate NearTable_analysis to find closest interstate distance
arcpy.GenerateNearTable_analysis(citiesL, interstates, nearestInterstate, maxKmInterstate)

# join new city list layer to generated Near Table
arcpy.AddJoin_management(citiesL, "NEAR_FID", nearestInterstate, "IN_FID")

# Run the Spatial Join tool, using the defaults for the join operation and join type
arcpy.SpatialJoin_analysis(targetFeatures, joinFeatures, outputLayer, "#", "#", "#")





print arcpy.GetMessages()
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)

# save selected features FINAL OOTPUT here
# arcpy.CopyFeatures_management(citiesL, outputLayer)

print arcpy.GetMessages()
[\CODE]

Python Add-In: Modifying an existing add-in?

$
0
0
Hopefully I am just overlooking the obvious here, but how do I go back to modify an add-in? I used the Add-In Wizard (addin_assistant.exe) to create the original, but now I want to add additional controls (tools, combobox, etc..).

That particular wizard seems to only be for creating the add-in.

Thanks for any help!
j

Question about Finding Sample Python Scripts!!

$
0
0
I am in the need of some python scripts that I might be able to adapt to a program I have to write here at work. I need to write one for finding missing annotation in an mxd and one for comparing two fields of data from seperate shapefiles. Can anyone direct me to the website or provide the link. Thanks!!

Clear Selected Features in All layers

$
0
0
I am looking for a way with python to clear all selected features in my dataframe. Like the "Clear Selected Features" button in ArcMap.

I have been looking for this online and just could not find it.

The only thing I can find is SelectLayerByAttribute_management(in_layer_or_view,"CLEAR_SELECTION")
The problem there is, that I need to feed it a specific layer, but I want to clear the selection in every layer.

Anyone know the answer?

Can you summarize a table by one field and the find median value of another?

$
0
0
I have a table of values collected at various monitoring stations. There's a row for each value with the station where and date when this value was recorded . I am trying to find a way to select all the values that fall within a certain date range and summarize them so there is only one value per station based on the median value. The "Summary Statistic" tool would work if I needed a sum or mean, but it does not have 'median' functionality. I was wondering if there was a python script that acts like the "Summary Statistic" tool but with the ability to find medians.

I'm using 10.0 at the ArcInfo level, any help is appreciated.
Viewing all 2485 articles
Browse latest View live