Hot answers tagged

19

I'm not aware of anything in the arcpy API that will do the scaling for you, but writing a function to do so would be relatively simple. The code below does the scaling for 2D features, and doesn't take into account M or Z values: import arcpy import math def scale_geom(geom, scale, reference=None): """Returns geom scaled to scale %""" if geom ...


14

The area of a circular buffer is a monotonically-increasing function of buffer radius (on a planar coordinate system anyway). So a simple search strategy can find a radius R such that the area of the buffer of radius R clipped to polygonal region A is (up to some tolerance) s. The simplest search algorithm would just be a binary search. Start with two ...


13

If the length of the ID field values is always constant I would recommend using either Field Calculator or Calculate Fields tool with python slices. TOWN calculation: !ID![:8] ERF calculation !ID![8:16] PORTION calculation !ID![-5:]


13

I am not so sure that this is a CPU-bound task. I'd think it would be an I/O-bound operation, so I'd be looking to use the fastest disk to which I had access. If E: is a network drive, then eliminating that would be the first step. If it isn't a high performance disk (<7ms seek), then that would be second. You may achieve some benefit from copying the ...


13

Iterate through all files in the shapefile directory with a valid shapefile extension and add their sizes together. The os module is helpful for this task. Here's a function that returns the size of all shapefile files associated with an input shapefile in bytes. Use the full path of the shapefile as your input. import os def ShpSize (inShp): ...


12

Do a set difference: s.difference(t) s - t new set with elements in s but not in t Ex: l1 = ['apple','banana', 'celentro', 'donut', 'elephant', 'film', 'gopher','hyena',1,2,3,4,5] l2 = ['film', 'celentro', 'badger', 'tiger', 100, 2, 4, 16] >>> set(l1).difference(set(l2)) set([1, 3, 'apple', 'gopher', 'hyena', 'donut', 'elephant', 'banana', ...


12

Let me guess: Your cpu has 4 cores, so 25% cpu usage, is 100% usage of one core, and 3 idle cores. So only solution is to make the code multi threaded, but that is no simple task.


10

I'm going to throw an answer on here because both answers thus far aren't 100% correct. There are 2 items which can vary from tool to tool. if it honors the workspace environment (this item is always doc'd on the tool help page) if it can make use of the in_memory workspace (this item may not be explicitly documented. You're more likely to see a note if ...


10

I assume you have installed comtypes successfully, according to the following SE Q/A: -How do I access ArcObjects from Python? import arcpy from snippets102 import * from comtypes.client import GetModule, CreateObject import comtypes.gen.esriFramework as esriFramework import comtypes.gen.esriArcMapUI as esriArcMapUI import comtypes.gen.esriCarto as ...


9

Python is treating \t as tab so you are really doing C{TAB}est you need to escape with \\ or use a raw string using r e.g r'C:\test_script'


9

If you have the XY of the point, then you could create a PointGeometry. current_sr = arcpy.SpatialReference(102726) #Enter the current WKID for the point new_sr = arcpy.SpatialReference(4326) #This is the WKID for WGS84 point = arcpy.PointGeometry(arcpy.Point(7334719, 670307), current_sr) new_point = point.projectAs(new_sr) >>> ...


9

If you have Arc 10.1 or above, I'd use an arcpy.da cursor. Also specify just the field(s) you want. myLayer = 'YourLayer' myField = 'YourField' myList = [row[0] for row in arcpy.da.SearchCursor(myLayer, myField)]


9

Try arcpy.GetInstallInfo() You'll get a dictionary of keys and should be able to write some logic on that {'SourceDir': u'C:\Users\kevi5105\Documents\ArcGIS 10.3\Desktop\SetupFiles\', 'InstallDate': u'5/5/2015', 'InstallDir': u'c:\program files (x86)\arcgis\desktop10.3\', 'ProductName': u'Desktop', 'BuildNumber': u'4322', 'InstallType': u'N/A', ...


9

Here is an arcpy soloution: import os, sys, arcpy InFC = sys.argv[1] OutFC = sys.argv[2] #split the output into directory and name Folder = os.path.dirname(OutFC) Name = os.path.basename(OutFC) # Get the existins spatial reference as it's going to match desc = arcpy.Describe(InFC) SR = desc.spatialReference # create or append if not ...


9

Create a raster object using the full path to your raster. Raster objects have the properties minimum and maximum. >>> rastFullPath = r"C:\Rasters\rasters.gdb\Slope" >>> rast = arcpy.Raster (rastFullPath) >>> rast.minimum 0.0 >>> rast.maximum 64.9616928100586 Or you can use your method and convert the output from ...


8

The problem is that your string inputFeature_json has special characters that are not in the ascii encoding. If you have characters that are not in the english alphabet they can cause encoding errors. Try to convert the string as unicode. for example: # Script arguments inputFeatures_json = arcpy.GetParameterAsText(0) #wtite to file jsonFileName = ...


8

This is not exactly what you asked for, but a workaround could be to add both IDLE instances to your Send To context menu option. open %APPDATA%\Microsoft\Windows\SendTo choose > New > Shortcut specify the path and command for IDLE, eg C:\Python27\ArcGIS10.2\pythonw.exe "C:\Python27\ArcGIS10.2\Lib\idlelib\idle.pyw" repeat for the other IDLE version Now ...


8

To add a custom toolbox, in ArcMap or ArcCatalog, open ArcToolbox and right click in the white space and go to Add Toolbox: To see the script, right click on the tool, and go to Edit or Export Script. If you use Export Script, create a new text file and select it when exporting. You might need to go into the Geoprocessing menu, and go to Geoprocessing ...


8

The problem is with the dash (-) in the shapefile name. This restriction is from geoprocessing tool and not the shapefile name since you can have dashes in your shapefile name. Geoprocessing methods exist that allow you to validate table and field names. Consider using either the ValidateTableName or ValidateFieldName function to ensure your name is valid


8

Wildcard searching is built into arcpy.ListRasters(): import arcpy arcpy.env.workspace = "c:/base/data.gdb" for raster in arcpy.ListRasters("*_*"): arcpy.Delete_management(raster) If you want more advanced wildcarding/filtering, you'll need to use regex.


8

This should do the trick: import arcpy import os def polysToPoints(in_polys, out_points): """converts polygons to centroids in_polys -- input polygons out_points -- output points """ ws, name = os.path.split(out_points) sr = arcpy.Describe(in_polys).spatialReference arcpy.management.CreateFeatureclass(ws, name, 'POINT', ...


7

A good starting point to understanding this is a help page entitled Understanding the progress dialog box in script tools: There are four functions you use to control the progress dialog box and its progressor. This certainly works for foreground Geoprocessing and I assume that it will have a similar effect on the Background Geoprocessing dialog.


7

Use the cursor.updateRow(field) instead of cursor.updateRow([field]). You should supply an object, not the list.


7

You could try something like this: import os, arcpy, glob from arcpy import env, sa from arcpy.sa import * check = arcpy.CheckOutExtension("Spatial") print check env.workspace = r'F:\Mosaic 2000' ws = env.workspace wsf= r'F:Mosaic 2000\Reflectance' rasters = glob.glob(os.path.join(ws,'*.tif')) bands = [['band1', 0.0508], ['band2',0.0254],['band3', ...


7

Use Python as the parser, and check the Advanced box. Then just replace yourFieldName with the name of the field you want to label. def FindLabel([yourFieldName]): value = [yourFieldName] first = False third = False if value[0] == "0": first = True if value[2] == "0": third = True if first == True and third == ...


7

A handy hint for 'special' folders is os.environ.get Some environments that will help you on windows: AGSDESKTOPJAVA ALLUSERSPROFILE APPDATA COMPUTERNAME HOMEDRIVE HOMEPATH LOCALAPPDATA NUMBER_OF_PROCESSORS PROCESSOR_ARCHITECTURE ProgramFiles ProgramFiles(x86) PUBLIC SystemDrive SystemRoot (don't write here, but it's handy for reading) TEMP TMP USERNAME ...


7

STEPS: Compute sections centre points: Built their Euclidean minimum spanning tree, dissolve it and compute buffer, distance equal half of shortest section length: Create section end points and compute their chainage (distance along line) on the boundary of the buffer (closed polyline version of buffer): Sort end points in ascending order using ...


7

Judging from comments, you might have it already :) You could compare the Well-Known Text (WKT) descriptions of the spatial references. sr1 = arcpy.Describe(dataset1).spatialReference sr2 = arcpy.Describe(dataset2).spatialReference sr1String = sr1.exportToString() sr2String = sr2.exportToString() if sr1String == sr2String: # Exact string match else: ...


7

as mentioned by @George, the randint takes a sample with repetition. If you want unique values, create a list of the required size and shuffle it. import random, arcpy listUnique = range(maxvalue) random.shuffle(listUnique) i=0 with arcpy.da.UpdateCursor(featureClass,[fieldToUpdate]) as cursor: for row in cursor: i=i+1 row[0] = ...


7

Check it with odbc and search if database contain table starting with GDB_ import pyodbc db_file = "C:/path/to/my/database/MyDataBase.mdb" user = '' password = '' odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;UID=%s;PWD=%s' % \ (db_file, user, password) cnxn = pyodbc.connect(odbc_conn_str) cursor = cnxn.cursor() if ...



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