Tag Info

New answers tagged

0

Although using the Soil Data Viewer is great. I was able to figure out how to accomplish what I originally set out to do. This document was a good resource. Extracting Soil Orders From STATSGO Instead of getting soil orders I wanted hydrologic groups. I used some python to combine all of the comp.txt files for the state of pennsylvania. I then brought this ...


2

The error in your "RastertoPolygon" script is due to a space in the file name of one or more of your input rasters. To confirm this answer, I ran your script on a folder of raster files and it worked perfectly. I added a space to the file name of one of the rasters and it failed with the message "ExecuteError: ERROR 010328: Syntax error at or near symbol ...


0

You can use Hawth Analysis Tool . It is very easy to use . You need to specify the number of sample to be drawn. Installation process in arcgis is here. Just select and export the layer. You can also use arcscirpt at here


3

The easiest way to do this is to use Python (can be run in Python window in ArcMap if you are not familiar with any IDE or Python prompt): import random print random.sample(range(800000), 240) This will give you a list of unique value (with no repeating), such as [1,2,5,12]. Now you can use the Select By Attributes in ArcMap and select the features which ...


0

This is how I would do it in model builder: Your sub-model takes a geodatabase and collects the contents into a list The Master model calls the sub-model but this has a precondition on it which is the calculate tool. This has a tiny piece of python code to test if the input geodatabase has a feature class called arc. You could adapt this for folders. ...


2

You're in need of a global variable where you can increment your new fid_1 field as CalculateField moves from record to record. Substitute this in for your last few lines of code: (Your first record will have a value of 0, the second will be 1, the third will be 2,...) codeblock = """id = -1 def getCalc(): global id id += 1 return id """ ...


0

What Python IDE are you using? Most have python path explorers. This is an example from PyScripter. The order of the path is also important particularly if you installed ArcGIS after you had a version of python installed. In this example, I have PyScripter installed as well as PythonWin. The latter was installed after ArcGIS to ensure that it was within ...


2

For brevity's sake: def FindLabel ([field]): val = [field] return ''.join([j for i, j in enumerate(val) if j != '0' or i == 1]) Step through the string and toss away all 0's unless it's in the middle position (index of 1), then join what's left.


1

Just for good measure, here's a way to use python string methods. This would work with strings of variable length, though I know that wasn't a consideration in this case: def FindLabel(value): if value.endswith("0"): value = value[:-1] # slice all but the last character if it's a 0 return value.lstrip("0") # take off any leading zeros


2

Here's a little more concise way of doing it. Basically convert it to a list and replace list[0] and list[2] with '' if the value is 0 def FindLabel([field]): value = [field] l_value = [x for x in value] # turns string to list no_zero_positions = [0,2] # where you don't want zeros for p in no_zero_positions: if l_value[p] ...


4

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


1

I added a call to get the traceback object to your previous script (Batch merging field mapping). I added a shapefile with an "Acres" field that was one character wide, and got this traceback message: ERROR 001156: Failed on input OID 0, could not write value '340.417' to output field Acres My working version of your script, set up to run in Idle, is ...


1

I would've just commented but my rep is too low. As Stimson has suggested, go Python. I would think that a simple if statement with the conversion process nested inside of it would work. So: for fc in arcpy.ListFeatureClasses(): if arcpy.Exists('arc'): SelectData_mb (in_dataelement, {out_dataelement}) ...


2

One way to tell if arcpy is installed is to go into Add/Remove Programs, select ArcGIS 10.2 for Desktop, and click the Uninstall/Change. When the ESRI window opens, select Modify and then click Next, and on the following screen Python should not have a red X on it. If it does have a red X, then you can change it to install the feature. Another way to ...


1

Tool validators are not easy to program, there's no debugging or text output so all you get is does/doesn't work. I notice that your if rows.next(): is on an incorrect indent level which could be why it isn't working. I also notice you're equating the self.params[3].value==True: where the value should be a path to a feature class.. not sure what's going on ...


1

I just experienced the same problem. It looks like ArcGIS is caching the tools/scripts. If I refresh (F5) the toolbox, after a few seconds the toolsets and tools would show-up and work, but next time I open ArcCatalog it shows the red crosses again. If you rename the folder where the PYT is stored, it won't show the red crosses the first time, only after ...


4

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


0

I have eventually got it working with SearchCursor and Select_analysis arcpy.env.workspace = strInPath # create a set to hold the attributes attributes=set([]) # ---- create a list of feature classes in the current workspace ---- listOfFeatures = arcpy.SearchCursor(strInPath,"","",strFieldName,"") for row in listOfFeatures: ...


1

I got it to run on a directory full of parcels, PLSS, and annexations. The directory had a mix of shapefiles and file geodatabases. I defined the datapath differently, but otherwise changed nothing. It failed on the 13th polygon feature class. The resulting shapefile had 62 fields and 44525 records. My failure was a type mismatch, so it was different than ...


0

I'm not familiar with the Iterate Feature Selection tools in ModelBuilder, but exporting just that as Python code indicate that they can be called using arcpy. # Created on: 2015-05-19 15:26:10.00000 # (generated by ArcGIS/ModelBuilder) # Description: # --------------------------------------------------------------------------- # Import arcpy module ...


0

You can use a geometry token (SHAPE@) within Copy Features (Data Management) to export each feature. import arcpy, os shp = r'C:\temp\yourSHP.shp' outws = r'C:\temp' with arcpy.da.SearchCursor(shp, ["OBJECTID","SHAPE@"]) as cursor: for row in cursor: outfc = os.path.join(outws, "fc" + str(row[0])) arcpy.CopyFeatures_management(row[1], ...


0

In Arcpy, Cursors honor layer/TableView selections. By according to this SE question, you can simply iterate feature selections. However if you want to make a selection using arcpy, use SelectLayerByAttribute_management tool.


3

You do not need to delete the row/cursor objects when using the with statement, this will automatically clean up when __exit__ is called after the cursor has exhausted itself. Also, it is easier to reference the fields by index because the rows are returned as tuples: with arcpy.da.UpdateCursor(polyline, ["SEWER_TYPE", "Layer"]) as cursor: for row in ...


0

The following requires a Spatial Analyst license. The ArcPy Raster Object provides a pretty intuitive interface to working with rasters. Once a Raster Object is created, you're allowed to perform math operations on it in a very similar manner to operations on python built-in objects. Properties and methods onboard the Raster Object should also be useful for ...


1

I would avoid using ArcGIS (arcpy) in this case and do this using a pure Python solution. This will be faster and much cleaner. Since you are renaming tif files you do not need to use ListRasters() or arcpy.Rename()...see this example: import os import glob def rename_files(new_names_file, file_folder): files_list = glob.glob(os.path.join(file_folder, ...


3

You can do this sort of renaming by utilizing enumerate. The general idea is to add an index with each raster name and then call that index to reference the specific item in the text file list. import arcpy arcpy.env.workspace = r'C:\path\to\input\rasters' txtfile = r'C:\path\to\textfile.txt' # Generate a list of items from text file with open(txtfile, ...


2

You can't really change the symbology of a layer in arcpy with the level of customization you have when just right clicking a layer and using the symbology menu. However, you can make a "template" layer that contains the symbology you want and then use ApplySymbologyFromLayer_management (in_layer, in_symbology_layer). This will allow you to apply the ...


3

It is not possible to change the properties of a layer directly. The properties of a layer can be changed, but only by importing properties from another layer in the map or a layer file. Even the layer name cannot be changed without an existing layer or layer file. "UpdateLayer" in the ArcGIS Help can give you more details and some examples.


6

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


0

You are probably trying to output Unicode characters into the terminal which does not know them. I'd suggest writing the results to a file instead, so that you can do something like this: import arcpy,os,fnmatch,unicodedata,codecs rootPath = r"C:\Project\layers" pattern = 'mig*.shp' with open('results.log', 'w') as logfile: for root, dirs, files ...


2

If you are running the tool outside of ArcGIS session, in Python (or when in the Python window and the extension has not already been enabled), you will need to check out an ArcGIS Spatial Analyst extension license before running a tool. You do it with: arcpy.CheckOutExtension("Spatial")


3

The output workspace and the FC name need to be properly concatenated. You can do this by using os.path.join(). # import system modules import arcpy, os from arcpy import env # Set environment settings arcpy.env.workspace= arcpy.GetParameterAsText(0) # type = workspace arcpy.env.overwriteOutput = True fcs = arcpy.ListFeatureClasses() # get buffer ...


1

Arcpy geoprocessing fails with file names that contain special characters like spaces or periods. I ran into this recently when I was able to use os.walk to read file names that contained periods, but arcpy.da.walk failed. I learned more about this problem in the help topic "Validating table and field names in Python". Please try your script again with no ...


1

arcpy.mapping (LegendElement) should do the trick. http://resources.arcgis.com/en/help/main/10.1/index.html#//00s300000041000000 Allows you to access properties of elements and reposition, etc.


1

It looks like you don't actually produce an output from your tool, only modify the input file. Although you have an argument for outFc you're not creating the output. Notice: all fields added and field calculations are performed on the input feature class. If you change your outFc to: outFc = arcpy.GetParameterAsText(2) the user can specify an output ...


1

If you want your users to be able to run your tool from ArcGIS application (such as ArcMap) and write output data into a known location, you should use arcpy.env.workspace in your code. For you it will be C:\\Users\\schalla\\Documents\\ArcGIS\\Default.gdb. Test yourself running arcpy.env.workspace from Python window in ArcMap. import os ... outputFc = ...


-1

You are better off using the scratchGDB workspace. Esri guarantees this path to exist for any user. import arcpy import os GDB = arcpy.env.ScratchGDB output = os.path.join(GDB, "FeatureClass") This method uses the default path to the scratch workspace environment which removes the need to know a specific file path. You can look here for other ways to ...


2

Geoprocessing tools (with the exception of Spatial Analyst tools) return a Result object, which is what arcpy.ApplySymbologyFromLayer_management returns here. It doesn't have a save method. You may be getting this mixed up with a MapDocument or Layer object.


2

One thing to remember, all actions that involve the parameter should be off the parameter object; so use parameters[n].setErrorMessage(msg) instead of arcpy.AddError(msg). AddError is used to add error messages into the tool execution messages, setErrorMessage is to add an error to the parameter that will block the tool from executing. So you also don't need ...


2

It looks like you need to pull out the name of the file from "inRaster" and add it into your "outname" variable. I've copied your last block of code and added comments to the lines I've added/edited. If the rest of your code is working as you indicate, this should take care of fixing the name and writing it where you want it. inRaster = ...


2

row.getValue() is used with arcpy.UpdateCursor, but with the "da" you should use the index of the field based on the field list that you provide (which can take a subset of the fields). fields = ["Flowline_In","FLowline_Out","Elevation_Gained"] elcursor = arcpy.da.UpdateCursor("AnalysisCreeks",fields) for row in elcursor: row[0] = row[1] + ...


2

You would need to look into some Help pages. Add the layer to the TOC. Get parameter (country name) as text. Get your cities into an array with arcpy.da.SearchCursor and do simple math with Python.


2

This kind of task is best approached by using the tool validator; you can set value of a parameter by reading another parameter's value (and listing feature classes from the workplace user specified). def updateParameters(self): if self.params[0].value: self.params[1].value = #ListFeatureClasses code else: If you want to populate a parameter with ...


0

Here is another way you can calculate a string to a text field: arcpy.CalculateField_management (fc, "DFDD", "\"aaa\"", "PYTHON") One way to verify formatting is to setup the tool/parameters in ModelBuilder and then export the model to a python script.


0

Put your expression (aaa) inside triple quotes: arcpy.CalculateField_management (fc, "DFDD", '"""aaa"""', "PYTHON")


1

As you can run your code (open a custom GP Tool) from within python window, then you toolbox path and its tool are ok. It can be a problem with your config.xml. Check this file and look for the button and make sure the Class and id of the button are set to ButtonClass1. e.g: <Button caption="GPToolDialog" category="Test Python Addin" ...


2

I asked too quick. According to this thread, the 1411380301000 value is: ...presented as epoch milliseconds since 01/01/1970 GMT. And I used the following code to convert it: import time value = 1411380301000 date = time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(value/1000.0)) print date >>> 09/22/2014 10:05:01


6

There is a large amount of documentation from ESRI on creating your own tools in Python, so I will assume that you can access your selected layer without issue. There are many methods for selecting data randomly, for example choosing in random number in the range of the number of features (using the random module as suggested by @MichaelMiles-Stimson above), ...


0

Your code is not going to work for these reasons: You need to add a wildcard "*" to ".mxd" and ".lyr" so that these return something (lines 3 and 4) You referenced "mxds" instead of "maps" on line 6, and it needs to be referenced as a arcpy.mapping.MapDocument because you need to save later. You need to nest the add each layer in a loop (line 8) You ...


2

This is complete working code (for what it's worth), one of the first arcpy tools I translated from 9.3 so it's still a little clunky.: import sys, os, string, arcpy InFolder = sys.argv[1] OutCoSys = sys.argv[2] ShapeName = sys.argv[3] #ShapeName = "JustFlightLinesNew.shp" ShapePath = InFolder ShapeFile = "%s\\%s.shp" % (ShapePath,ShapeName) if ...



Top 50 recent answers are included