Hot answers tagged

15

I can see several things that may be causing your script to be slow. The thing that is likely being very slow is the arcpy.CalculateField_management() function. You should use a cursor, it will by several magnitudes faster. Also, you said you are using ArcGIS Desktop 10.3.1, but you're using the old ArcGIS 10.0 style cursors, which are also much slower. ...


14

Add the two together, they are just lists. FCS = arcpy.ListFeatureClasses("X_*") + arcpy.ListFeatureClasses("*_Y") To eliminate duplicates: FCS = set(arcpy.ListFeatureClasses("X_*") + arcpy.ListFeatureClasses("*_Y"))


13

See Unpacking Argument Lists. Input for the Point object is for example X coordinate and Y coordinate as doubles: point = arcpy.Point(1, 2) In your example coords will be a list, like [1, 2]. This is unpacked with * into 1, 2


11

If they are all have the same name schema then you should be able to do the following: import arcpy arcpy.env.workspace = 'LOCATION OF THE GDB' fcs = arcpy.ListFeatureClasses("*cnty*","") for fc in fcs: arcpy.Rename_management(fc, "%s%s" % (fc[0:1],fc[-2:]))


10

Instead of looping over the current field names, you can loop over the field names you want to add. Let's say you have a list, to_add, containing the field names you want your feature class to have. You can then use the in statement to check if each item from to_add is in fieldList. The following should work: #List of field names to be added to_add = ["Area"...


9

Instead of iterating over the whole list returned by ListLayers, pass in the wildcard parameter using your layer name and just process the first item, e.g. import arcpy mxd = arcpy.mapping.MapDocument("CURRENT") lyr = arcpy.mapping.ListLayers(mxd, "layer_name")[0] desc = arcpy.Describe(lyr) print lyr.name fields = desc.fields for field in fields: print ...


8

Try explicitly defining the workspace: import arcpy arcpy.env.workspace = r'C:\path\to\your\ws' rasl = arcpy.ListRasters() The documentation shows that you cannot include the path of your workspace in the ListRaster function: The workspace environment must be set first before using several of the List functions, including ListDatasets, ...


7

Give this a try: import arcpy ds = "NAME OF DATASET" fields = [f.name for f in arcpy.ListFields(ds)] cur = arcpy.SearchCursor(ds) outlist = [] for row in cur: for field in fields: outlist.append(row.getValue(field)) break


7

Well, there are a few ways to go about this. Here is one approach: import arcpy from os.path import splitext #Use splitext, as slicing is hardcoded for extension length photos = arcpy.GetParameterAsText(0) #photos folder fc = arcpy.GetParameterAsText(1) #feature class arcpy.env.workspace = photos #Create list of image names without extension nameList = [...


7

Try placing the wellCntList list outside of the for loop. Otherwise, each iteration is writing over the results of the previous one--ultimately leaving only the last iteration's results. wellCntList = [] for cname in countyList: whereclause = "{} = '{}'".format("COUNTY", cname) wellCnt = 0 with arcpy.da.SearchCursor(Wells_Intersect_Layer, "...


7

There are dedicated list functions in arcpy and I would use them rather than the python os.listdir function: import arcpy, os workspace = r"C:\test" arcpy.env.workspace = workspace arcpy.env.scratchworkspace = workspace arcpy.env.overwriteOutput = True firstlevelList = arcpy.ListWorkspaces(workspace_type = "Folder") for element in firstlevelList: ...


6

You have erroneously nested a loop that is iterating over the same tif - i.e., basically on the innermost you have: while x is less than 100, loop on the tif list, increment x by 1 So the while loop executes inside your 'for' loop, starting with the 1st tif. The intended mechanism of the 'for' loop doesn't hand off successive list tifs because x has to run ...


6

You could approach it a bit differently: import arcpy import os arcpy.env.workspace = 'c:\temp' fcs = [fc for fc in arcpy.ListFeatureClasses() if fc.startswith('X_') or os.path.splitext(fc)[0].endswith('_Y')]


6

To do this you should use a combination of ArcPy and Python. You can use Python's enumerate function to get a number for each item in your list. You use arcpy.da.InsertCursor() to create and populate a new row for each item in the list.


6

An alternative method is to pass your list into a Structured Array and then convert that. When writing to a table it automatically puts in an ObjectID field. Below is some sample code. import arcpy,numpy try: # List of unique values, note this is a # list of lists with each list holding a single value myList = [[1],[2],[3],[4],[99]] # ...


6

Your last print statement is not indented properly. As it is now, your are calling it after, i.e not inside, the loop. To fix it, just put it inside the loop by adding enough space before. for shape in shapefiles shapeName = shape.replace('.shp', '') print shapeName


5

You need to grab the first element of each row and convert to int. listname = [] cursor = arcpy.da.SearchCursor(fires, "YYYYMMDD") for row in cursor: listname.append(int(row[0])) print 'the first fire date is {0}.'.format(min(listname)) print 'the last fire date is {0}.'.format(max(listname))


5

This StackOverflow answer has a more concise, Pythonic suggestion: >>> print list(izip_longest(*(iter(range(10)),) * 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)] You could incorporate it like this: from itertools import izip_longest for i, group in enumerate(izip_longest(*(iter(tifList),) * 100)): group = filter(None, group) # ...


5

Close! features = [[row.getValue (field.name) for row in arcpy.SearchCursor (fc)] for field in arcpy.ListFields (fc)] With da: features = [[r[0] for r in arcpy.da.SearchCursor (fc, field.name)] for field in arcpy.ListFields (fc)]


5

The * symbol indicates tuple unpacking. This can be very handy particularly when you have to call the same function many times with different arguments to get various parts of the returned object, but this results in repetitive code. Overview Python has a powerful technique called tuple unpacking where the tuple of values is unpacked into the variable ...


5

QgsVectorLayer class has a fields method for it. Using the QGIS Python console you can try this code (the current layer should be a vector layer (instance of QgsVectorLayer)): >>> layer = iface.activeLayer() >>> layer <qgis._core.QgsVectorLayer object at 0x7f5e031ccc18> >>> layer.fields() <qgis._core.QgsFields object at ...


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 ...


4

Are you remembering to set your arcpy.env.workspace before using the various arcpy list functions (ListRaster, ListFiles, etc.)? Also many arcpy functions do take Python list objects for some arguments. They are denoted in the help by syntax such as [input_raster,...]. Indeed, MosaicToNewRaster's input_rasters argument does. There may be other functions ...


4

There is an excellent blog post on this topic here: About geographic transformations and how to choose the right one You can find the list of all transformations and their Areas of use, at the bottom of this ESRI Knowledge Base article: HowTo: Select the correct geographic (datum) transformation when projecting between datums


4

I think your problem is that in its current state CLIPLAYERS is a string and not a list. This means that when you loop through it using for LAYERS in CLIPLAYERS it is going to give you one character at a time starting with C. You can avoid this by adding CLIPLAYERS = CLIPLAYERS.split(";") before you loop through CLIPLAYERS. This will create a list from a ...


4

Assuming you have access to ArcMap > 10.1, this is a one liner that will write your field information to a list. fname = "field1" fdata = [row[0] for row in arcpy.da.SearchCursor(shp, fname)] The code below will work if fname is a list. The resulting fdata will be a list of lists. fname = ["field1", "field2", "field3"] fdata = [[r for r in row] for row ...


4

Since you asked for a 1-liner: firstRow = next(([row.getValue(field) for field in (f.name for f in arcpy.ListFields(ds))] for row in arcpy.SearchCursor(ds)), None) This uses a generator expression and the next() built-in function to short-circuit the evaluation of the generator such that only the first row is fetched. The None argument avoids a ...


4

Yes - you need to use a Python list and process it using a for loop: import arcpy arcpy.CreateFileGDB_management("I:/python/MultipleFD2GDB", "HabitatAnalysis.gdb") fdList = ["EMI_EMF", "Cultural_Resources", "Parcels", "Hazardous_Materials", "Footprint", "Checkpoint_B", "Wetlands", "Botany", "Land_Use", "Buffers", "Air_Quality", "Transportation", "...


4

IQueryFilter is the best option for your problem.You can put your name value in the whereclause of the queryfilter and thereby you can get the desired feature. ESRI.ArcGIS.Geodatabase.IQueryFilter queryFilter = new ESRI.ArcGIS.Geodatabase.QueryFilterClass(); queryFilter.WhereClause = "NAME LIKE 'LIGHT_POLE'; ESRI.ArcGIS.Geodatabase.ICursor cursor = ...


4

Instead of: for fields in arcpy.Listfields(Feature): print fields try: for field in arcpy.Listfields(Feature): print field.name My changing of fields to field is not important but I think it makes the code read better. However, what is important is that ListFields returns a list of field objects and so you need to examine the name property of each ...


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