Hot answers tagged

10

A few things: Use "raw strings" to avoid issues with Windows path separators (backslashes) being interpreted as escape characters, e.g. Folded = r"C:\Documents \test.gdb" ^ note the r Is there really a space after "documents"? I suspect not Use os.path.join() to concatenate paths e.g. path = os.path.join(Folded, FileName15+"_table.dbf") There's ...


9

Please consider using an arcpy.da.SearchCursor: FieldNameDict = {} with arcpy.da.SearchCursor(dbf,[myfield,'AP_ZIP','AP_STATE','AP_CITY','AP_FULLADD','AP_BUILDIN']) as rows: for row in rows: FieldNameDict[row[0]] = row[1:] # everything but the first element As the row is a tuple that is returned you can use simple indexing [1:] to ...


8

Iterate over the dict items and construct a new dict from the key and sum of the values: >>> slackloopLength = {'abc': [1,2,4,7], 'def': [1,3,5,7,9]} >>> {k: sum(v) for k, v in slackloopLength.items()} {'abc': 14, 'def': 25} >>> The way to read this construction is: We're going to make a dict: { and each element will have ...


8

By default the auto commit interval is set to 1000. You can change the interval using the following: arcpy.env.autoCommit = 5000


7

You receive the error module 'arcpy' has no attribute 'CreatePersonalGDB_management' because this tool does not exist in ArcGIS Pro. ArcGIS Pro has no support for pGDB (personal geodatabases). Neither read, nor write. You need to start with a supported datatype before moving to Pro. Shapefiles, fGDB, etc. So before moving to Pro, use ArcMap, ArcCatalog, or ...


7

All geoprocessing tools produce a Results object. You want the first output of your GetCount results object. The output will be a string, so you also must convert the string to an integer. if int (arcpy.GetCount_management(PolygonNeighbor_TableSelect) [0]) > 0:


7

You can use python sets to calculate fieldsToDrop and loop over it to remove the desired fields like so: # Input point data inFC= "inFC" # CHeck if field exist,if yes, delete the field allFields = [f.name for f in arcpy.ListFields(inFC)] fieldsToKeep = ["OBJECTID", "Shape", "Country", "manualChange"] fieldsToDrop = list(set(allFields) - set(fieldsToKeep)) ...


7

Since your feature class is in GCS_WGS_1984, you don't need to specify any Coordinate System. Though, if you want to add coord_sys explicitly, you can use one of those: EPSG code as string e.g. "4326" EPSG code as integer e.g. 4326 SpatialReference object # as string arcpy.AddGeometryAttributes_management(parcel_feat, "POINT_X_Y_Z_M", "", "", "4326") #OR ...


7

Another way is to specify the spatial Reference by name, for instance, Geographic Coordinate Systems/World/WGS 1984. The following snippet tested on ArcGIS 10.5 and worked as expected: import arcpy from arcpy import env ws = env.workspace = r"F:\Ahmad\Test\PT" fc = "Cities.shp" sr = arcpy.SpatialReference("Geographic Coordinate Systems/World/WGS 1984") ...


7

The input to insertRow() must be a list or tuple. Instead of building this as a string value as listed above, dashboard_site_summary_list.append('((' + str(row[0]) + ',),') append a tuple: dashboard_site_summary_list.append((row[0],)) # don't forget the comma; see below for type comparison or list (whichever you prefer): dashboard_site_summary_list....


6

This is how I would do it (it requires the Spatial Analyst extension which I think you have): import arcpy from arcpy.sa import * arcpy.CheckOutExtension = "Spatial" ndvi_raster = Raster("ndvivaluefrompixel") grey_raster = Raster("grayscalepixelvalue") output_raster = Con(ndvi_raster >= -0.000005 * grey_raster + 0.314367, 2, 1) output_raster.save("C:/...


6

I have not tested this but it is a one liner that uses dictionary comprehension, an arcpy.da.SearchCursor() and the indexing syntax from the answer by @MichaelStimson: FieldNameDict = {row[0]:[row[1:]] for row in arcpy.da.SearchCursor(dbf,[myfield,'AP_ZIP','AP_STATE','AP_CITY','AP_FULLADD','AP_BUILDIN'])}


6

If your fGDB actually does have feature datasets (not just top-level feature classes), you could do: import arcpy import os arcpy.env.workspace = r"X:\311\Obtaining GIS Data\TaxParcels.gdb" # Get top-level feature classes featureclasses = arcpy.ListFeatureClasses() # Get data-set feature classes datasets = arcpy.ListDatasets() for ds in datasets: ...


6

Turn off Qualified Field Names before joining. arcpy.env.qualifiedFieldNames = False Tools that honor the Qualified Field Names environment use this setting to distinguish between qualified or unqualified field names. Qualified field names are the names of fields in a feature class or table that have the name of the origin feature class or table ...


6

buffCount looks to be a string, you need to convert that to an integer


5

Use GetCount to check if table is empty and da.InsertCursor to insert a row. I dont think you should try to set objectid, let it be set automatically. If you want your own ID then add another field for it. import arcpy table = 'C:\data.gdb\table123' #Change fields = ['freq','sum'] #Change if int(arcpy.GetCount_management(table).getOutput(0)) == 0: icur ...


5

Don't use try:...except: when debugging. Don't use silent and overly broad exception handling ever. Some comments: You're not using the csv module. You import it, then never use it, instead you manually read and parse the file as text. arcpy.Array doesn't have an Add method, it has an add method - python is case-sensitive You're mixing the old arcpy....


5

The code that you have presented is for a Python Toolbox (*.pyt) for which you need to use the Parameter class. GetParameter() and GetParameterAsText() are only used with Python Script tools in Standard Toolboxes (*.tbx).


5

Using the answer from @PolyGeo my corrected code is as follows: import arcpy class Toolbox(object): def __init__(self): """Define the toolbox (the name of the toolbox is the name of the .pyt file).""" self.label = "Toolbox" self.alias = "" # List of tool classes associated with this toolbox self.tools = [...


5

You need a colon after your line: if layer.supports(definitionQuery) should be: if layer.supports(definitionQuery): You should also consider modifying your query as was commented by @smiller. It will make your code easier to read.


5

You are messing with the iterated variable, mxd within the for loop, but worse than that, you are assigning it an object within the loop which is of a completely different class to what the iteration assigns it. You should use two different variables instead. So instead of this: for mxd in mxdnames: input = os.path.join(ws, mxd) mxd = arcpy....


5

If you want to stick to python you can use a dictionary mydict= { 'Oshawa': '70', 'Toronto': '71a', 'Mississauga': '85', 'Kitchener': '77', 'Sudbury': '65' } if !CSDNAME! in mydict.keys(): !ZONE! = (mydict[!CSDNAME!]) else: #do something to flag Or you could create a table and districts and names and do a join. A left outer join (...


5

The token "SHAPE@XY" populates the geometries of the feature. You won't see the results in your output table. If you have fields for X and Y use their names instead of "SHAPE@XY". with arcpy.da.InsertCursor(fc,['Sp','X', 'Y']) as iCurs: with arcpy.da.SearchCursor(fc, [X, Y, ID]) as sCurs: for row in sCurs: row = (row[2],row[0],row[1])...


5

From the InsertCursor documentation: Opening simultaneous insert or update operations on the same workspace using different cursors requires the start of an edit session. Since you're not closing the cursor, it remains open during the next run. Try using the following pattern instead: with arcpy.da.InsertCuror('points', ['SHAPE@XY', 'Id']) as cursor: ...


5

You have the general idea in place already -- just move your print of the list into the loop, and remove the print for each vertex. import arcpy fc=r'D:\GIS Data\TOOLS\EV calc in Python\Data.gdb\PolyWGS84' with arcpy.da.SearchCursor(fc,['OID@','SHAPE@']) as cursor: for row in cursor: myList = [] array1=row[1].getPart() for ...


5

You cannot use "CURRENT" in a Geoprocessing Service. The GP Service has no idea what "CURRENT" is as the service isn't an open session of ArcMap. CURRENT is reserved for working with a script inside ArcMap only. To use arcpy.Mapping, specifically a reference to a map document, you need to provide the full path to the MXD in place of CURRENT. mxd = arcpy....


5

Use arcpy and check each row of the table using da.SearchCursor and list ObjectIDs of the rows matching your condition. Then select using the list. Adjust and execute in python window: import arcpy layer = 'somelayeraddedtothemap' #Change field_to_check = 'somefield' #Change oidfield = arcpy.Describe(layer).OIDFieldName #What is the oid fieldname #List ...


5

The indentation errors are unrelated to the name of the mapping module. As @smiller comented, you are probably mixing tabs and spaces. If you want to make sure, download Notepad++ and open your Python file by right clicking it and selecting Edit with Notepad++. Once Notepad++ is open, click on the Show All Characters button It will show all special ...


5

They're Field objects, you need to print the Field.name property: [f.name for f in arcpy.ListFields(your_fc)] Example from the Help: Code sample ListFields example - List field properties. import arcpy # For each field in the Hospitals feature class, print # the field name, type, and length. fields = arcpy.ListFields("c:/data/municipal.gdb/...


5

No, the problem does not have anything to do with ArcGIS or arcpy. SyntaxError means that there is a problem with the syntax of your program and it identifies this error before running anything. In your case, you have an opening parenthesis that should not be there and is triggering the error. On the line: structureMultiplier = (arcpy.GetParameterAsText(5) #...


Only top voted, non community-wiki answers of a minimum length are eligible