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


15

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


14

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


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


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.


12

row[0] simply refers to the first field in your list of fields in the cursor. Since you only have one field in your list, "PERIMETER", then row[0] refers to that field. If you had multiple fields, ["PERIMETER","AREA","POPULATION"] that were being searched or updated in your cursors, then row[0] would be "PERIMETER" row[1] would be "AREA" row[2] would be ...


11

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


10

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)]


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


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

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() matching = False if sr1String == sr2String: # Exact ...


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


9

It looks like Indicator may be a reserved word in .mdb Access Databases. See Learn about Access reserved words and symbols. Changing the Indicator field name to something else eg Indicator1 should work: #import tools and set workspace import os import arcpy arcpy.env.workspace = r"C:\Users\sutton\Documents\Python\PythonExcercise\PlanoData.mdb" try: ...


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


8

You need to: Use an update cursor Split the string into a list Remove duplicates Put the list back into a string Assign the string to that row/field Apply the update Try this: import arcpy duplicates = "G:\\xStreetNew\\Duplicates.shp" with arcpy.da.UpdateCursor(duplicates, ['Intersecti']) as cur: for row in cur: row[0] = ...


8

If you want to use the Calculate Field tool (instead of an Update Cursor), what you're assigning to val needs to be an unevaluated python expression. That is, it needs to be identical to the string you would type into the Calculate Field tool if you were using the GUI version. What you're currently assigning to val is "!FEDIRP! !FENAME! !FETYPE!". Any of ...


8

Python window is not an equivalent of the Python shell; hence, you won't be able to use the raw_input there. To implement the interactivity with the user, you may choose any of these alternatives: build custom script tools with input parameters (via arcpy.GetParameterAsText()); build Python add-ins (which have text boxes to fill in); use 3rd party Python ...


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

With cursors and the "SHAPE@" token, a geometry object is returned. The getPart() method returns an Array containing all the points for that particular part. Interestingly, field calculator also returns a geometry object, but the getPart() method does not appear to return an array, although it is something similar. Maybe an unpacked array? Luckily, arcpy ...


7

I think the speed problem you are having is looping around each feature and using geoprocessing tools inside the loop. They are not designed for that. They expect to process the whole dataset at once. So restructure your script to avoid the loop and it should complete "within the time to drink a cup of coffee". The data is in my opinion so small that it ...


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

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


7

When you click "Run" or call python mytoolbox.pyt, your code does not do anything other than define the classes and import some modules. You haven't actually told python to run the tool. The best way to run your tool is using arcpy.ImportToolbox from another script or from the python prompt as per PolyGeo's answer. However, what I sometimes do for ...


7

Your set of points does not create a closed line where the first and last point are the same. Polygons are made up of closed lines. Try adding the same point that you start with at the end of your array. Edit: FelixIP's comment contains the correct answer about using arcpy.Array(). Closing lines used to create polygons is a good practice, but it is not ...


7

You can also deploy addins by copying the .esriaddin file to a network location and telling the addin manager to search this folder. This location can be added to every PC in your organisation using group policy to set a registry key. See the last section of this page for more details.



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