New answers tagged

2

You are creating the same feature layer for each row, of the entire shapefile. Then rasterizing the shape. Add a where clause to only make a feature layer of current cursor row and rasterize "Layer" : ... with arcpy.da.SearchCursor(shp, PIDname) as sCur: for row in sCur: out_Raster = "PID{}.tif".format(row[0]) sql = &...


2

Working from @PolyGeo's answer, here's some code that gets the info out of ArcMap: import arcpy srcPath = "D:\\SomeFolder\\Data\\" srcFile = "MyMap.mxd" # set working mxd mxd = arcpy.mapping.MapDocument(srcPath+srcFile) with open(srcPath+'filename.txt', "w") as outtxt: for df in arcpy.mapping.ListDataFrames(mxd,"*"):...


3

Rather than output bookmarks as an ArcGIS Place File (*.dat) you can use the ListBookmarks function of ArcPy which: Returns a Python list of named tuples that provide access to each spatial bookmark's name and extent. With that simple data structure available within Python you could write to a file format of your choice or just read it direct using PyQGIS.


1

Vince was correct, set polyline as my index layer. Made a copy of the index layer and used it to use Page Definition queries. Credit: How do I only show current index polygon extent in Data Driven Pages


1

You cannot append new data into existing by just copy/paste or conversions. It will try to replace you existing table. If you have updated your table previously and you want to replace you existing table, all you have to do is to insert this line after importing arcpy. arcpy.env.overwriteOutput = True However you should take a look to append tool. Pay ...


0

As the error message said, the parameters are not valid. And as @Vince commented, the particular parameter that is invalid is the first one, the layer. To see what parameters are valid, check the documentation at: https://desktop.arcgis.com/en/arcmap/latest/tools/data-management-toolbox/select-layer-by-location.htm The first parameter should be a feature ...


1

Here's how I did it: Set up the field mappings object Set up a nested Python dictionary with details on the fields I wanted Looped through that to add each individual field mapping Then the field mappings object could be used in the TableToTable_conversion Kudos to this answer to Using Field Mapping with TableToTable_conversion in arcpy for leading me down ...


0

Very nearly thanks BERA - but \W includes "(" and ")" as well as spaces, dashes and underscores. I think building on your code and, looking at the help for re (https://docs.python.org/3/library/re.html), this does it (uses only spaces, dashes and underscores): import re fc = r'my dbf file' fieldnames = ['inField','outField'] with arcpy....


2

The easiest is probably to chain replace: import arcpy fc = r'C:\data.gdb\features' fieldnames = ['infield','newfield'] with arcpy.da.UpdateCursor(fc, fieldnames) as cursor: for row in cursor: row[1] = '_'.join(row[0].replace('-',' ').replace('_', ' ').split()).title() cursor.updateRow(row)


2

I found the solution myself. If you use the arcpy.CalculateRepresentationRule_cartography() fucntion on your FeatureClass, it generates a RuleID field in the FC. Now, you can use SearchCursor() with sql to filter objects: sql = "FID > 3" cursor = arcpy.SearchCursor(featureClassPath, sql) for row in cursor: print(row.getValue("RuleID&...


3

There's a number of issues here: Both row[0] and row2[0] are already PointGeometry type objects, for which .firstPoint is the Point accessor property. Use the arcpy.Array object to bundle the Points, as in the documentation. Never, never, never use a Geometry constructor (arcpy.Point, arcpy.Polyline, arcpy.Polygon) without the SpatialReference of the target ...


5

Create a pandas dataframe from your data and use to_csv. A workaround, but you can choose whatever delimiter you want: import arcpy import pandas as pd fc = r'C:\GIS\data\Bakgrundskartor_LMV\Vagkartan.gdb\bs_riks' #fields = ['KKOD', KATEGORI','SRIKT'] #Either list the field names manually fields = [f.name for f in arcpy.ListFields(fc) if f.type not in ('...


2

There is an ArcGIS Pro Idea already submitted to Add More Delimiter Options in Table Export Tools (i.e., pipe delimiter): There are several existing tools to export a table to a flat file .txt or .csv, such as copy rows, table to table, or export features rows to ASCII. The last option at least gives you the ability to choose comma, space, or semicolon ...


2

You can use ArcPy: import arcpy, itertools arcpy.env.overwriteoutput=True arcpy.env.workspace = r'C:\GIS\ArcMap_default_folder\Default.gdb' #Change points = r'graphpoints' #Your input points pointlist = [p[0] for p in arcpy.da.SearchCursor(points, 'SHAPE@XY')] #List all points pointcombinations = [p for p in itertools.combinations(pointlist, 2)] #List all ...


1

You want to resample each raster to 2, 3, 4, 5 meters? Use a for loop with range: import arcpy, os arcpy.env.workspace = r"C:\GIS\data\testdata\Rasters\Folder1" out_folder = r"C:\GIS\data\testdata\Rasters\Folder2" for r in arcpy.ListRasters ("*", "TIF"): for resolution in range(2, 6): out_raster = os.path....


1

Using BERA's suggestion this is the dictionary that was successful in creating the soil class values. fc= r'D:\GIS\PollinatorProject\Pollinator\Pollinator.gdb\soil_samples' fields = ['L1_SOILTYP', 'ClassofSoil'] type_to_class = { 'CLAY, DUMP': '1', 'DRY CLAY': '1', 'Clay' : '1', 'CLAY' : '1', 'CLAY MOIST' : '1', 'CLAY(WEATHERED ...


1

You are not constructing the field mapping correctly. It's quite fiddly to set up but once you have done it, it is very powerful way of bringing datasets together be it a Merge or Spatial Join. I recently had to merge many dbf files, the product of some zonal statistics analysis I had done. Below is a function that takes a list of files and constructs a ...


1

See: https://community.esri.com/t5/python-questions/listing-layers-in-a-group/td-p/736543 proj = arcpy.mp.ArcGISProject('CURRENT') m = proj.listMaps()[0] ml = m.listLayers() for l in ml: if l.isGroupLayer and l.name=='somegroupname': print(l) lyrs = l.listLayers() for lyr in lyrs: print(lyr)


2

You can use a dictionary to shorten your code: import arcpy fc = r'D:\GIS\PollinatorProject\Pollinator\Pollinator.gdb\soil_samples' fields = ['L1_SOILTYP', 'SoilClass2'] type_to_class = {'CLAY,DUMP':'1', 'CLAY(WEATHERED SHALE)':'1', 'FILL,CLAY':'1', 'SAND':'2', 'TOO SANDY':'2', 'Sand, coarse':'2', 'COARSE SAND':'2', 'Sandy ...


1

If you want to classify your data using natural breaks, a way of doing it in python is to import a module that does this for you. A simple google search threw up the jenkspy module. I've not used it so can't comment on its ease of use/stability but it appears to do what you need. Also have a look at this Q&A using a pysal module approach.


-1

ApplySmbologyFromLayer is buggy and I haven't been able to get it to work from a Python Script e.g. https://support.esri.com/en/bugs/nimbus/QlVHLTAwMDExOTkwNw== Keep subscribing to the bug and logging it as a bug if you have support and ESRI may get around to fixing it.


0

For those who are interested in my solution: import arcpy import ConversionUtils arcpy.env.workspace = "C:/path" arcpy.env.overwriteOutput = True in_features = ConversionUtils.gp.GetParameterAsText(0) in_features = ConversionUtils.SplitMultiInputs(in_features) in_dist = arcpy.GetParameterAsText(1) in_dist = ConversionUtils.SplitMultiInputs(in_dist)...


7

You get the error because you pass a list for the first parameter. Instead, use the tool in for loop with path of the file. import arcpy import os arcpy.env.overwriteOutput = True input_path = "G:\\Python\\Arcgis\\Materials\\" output_path = "G:\\Python\\Arcgis\\Buffer\\" shapelist = os.listdir(input_path) shapelist = [x for x in ...


1

You need to explore the helpfile and read up on what is referred to as a python toolbox. This will allow you to build the tool interface that will allow your users to select multiple layers and assign buffer distances to each layer. You need to define what is called a ValueTable.


0

So, apparently insertCursor demands a list object. With the following, the code works. I'll leave it here for posterity; if mods want to remove the question in case they find it too basic, that's fine too. def get_extent_centroid(layer): desc = arcpy.Describe(layer) if desc.dataType in ['FeatureLayer', 'RasterLayer']: extent = desc.extent array = ...


0

The below worked for me and returned a list of field names with data type and data length: import arcpy # For each field in the Hospitals feature class, print # the field name, type, and length. fields = arcpy.ListFields(r"C:\Users\utilavt\Documents\ArcGIS\Parcel_Updates\shps\PARCELS.shp") for field in fields: print("{0} is a type of {1}...


2

Below is the code required to alter the Halo of a Text Symbol. I have to say it's not particularly clear from the help file how to do it and it took me some time to work it out. The Python CIM access page was useful. aprx = arcpy.mp.ArcGISProject("current") myMap = aprx.listMaps("Map")[0] myLayer = myMap.listLayers("Home")[0] ...


3

Try this: import arcpy, os arcpy.env.workspace = r'C:\GIS\data\testdata\clip' #Your folder with the shapefiles to be clipped outfolder = r'C:\GIS\data\testdata\clipout' cutter = r'C:\GIS\data\testdata\clippolygon.shp' for fc in arcpy.ListFeatureClasses(): #List shapes in workspace print 'Clipping: ', fc arcpy.Clip_analysis(in_features=fc, ...


1

I have no clear answer on how to reclassify vector data. For reclassifying raster data in ArcPy however, you can best use the "Slice" method. Here you can specify the classification method yourself. You can find documentation on it here: pro.arcgis.com/en/pro-app/latest/tool-reference/spatial-analyst/…


1

A variant on @FelixIP's approach is first take one of your rasters and run it through the raster to point tool. This creates a point for every pixel. You now have a point dataset which you could apply a selection to, e.g. a particular catchment, then run it through the Sample tool as he describes above.


1

Set environment extent and cell size to your raster. Make sure workspace is also specified. In Python window type: arcpy.gp.SingleOutputMapAlgebra_sa("$$ROWMAP","nRow") This will produce integer raster of rows: Similarly compute raster of columns: arcpy.gp.SingleOutputMapAlgebra_sa("$$COLMAP","nCol") In Arcmap ...


1

When iterating over the layers in your loop, check layer.name for a match to the target layer name, and\or use the filter parameter in ListLayers to reduce the list to layers matching your target layer name. If adding a filter to ListLayers, you can operate on the first layer returned if you are confident there is only one possible match.


1

If you haven't converted your CSV to a table called "County-Case-Counts.csv" prior to running this script, you need to call TableToTable_conversion first, with a full path to the csv (which you have defined as "csv_file"). You can then call AddField_management on the GDB class you have created. import arcpy arcpy.env.workspace = r"C:...


1

Check your inTable variable. "County-Case-Counts.csv" That's the name of your file. Just double check that the name of the table here. The '.csv' part to me doesn't look right, usually tables are not suffixed by the filename. e.g.: If you imported a shapefile, the table name would be 'data'... not 'data.shp' Or possibly just this line is missing a ...


1

arcpy.env.workspace = r"C:\\" using a raw string, the interpreter will escape backslashes, so this will result in 4 backslashes. Remove the "r" as you have to escape to form a valid string. >>> dir = r"c:\\" >>> dir 'c:\\\\' here you are also prepending a backslash to the file name, so this will end up with 5 ...


0

I think you should look at this line of code: arcpy.env.workspace = r"C:\\" It does not look like a valid workspace so as a test try using: arcpy.env.workspace = r"C:\temp"


1

I believe the only thing you need to change is your legend dictionary to: legend_dict = {'0': {'RGB': [255, 85, 0, 100]}, '1': {'RGB': [0, 92, 230, 100]}, '2':{'RGB': [132, 0, 168, 100]}, '3':{'RGB': [56, 168, 0, 100]}, '4':{'RGB': [255, 255, 255, 100]}} Note I have changed all the alpha settings from 0 to 100


1

You need to read the help file and understand what the syntax section is telling, then look at the sample code to get a good understanding of how to call the tool. At no point in the help does it indicate you can enter a list of fields as you have. It is AddField... singular! The syntax you appear to be using is for the ArcPro AddFields tool...plural! You've ...


0

Thanks everyone for your help. This is what my final script looks like import arcpy, os arcpy.env.overwriteOutput = True gdb = raw_input("please input the path of the GDB you are working with. >> ") arcpy.env.workspace = gdb in_fc = raw_input("Please input the fc name that requires utm coordinates. >> ").upper().strip() xy_fc =...


1

Try using da.UpdateCursor: import arcpy gdb = r'C:\data.gdb' verts = 'pointfc' in_feature = os.path.join(gdb, verts) with arcpy.da.UpdateCursor(in_feature, ["OID@", "PNT_TYP"]) as cursor: for row in cursor: if row[0] % 2 == 0: row[1] = 'PofT' else: row[1] = 'PofC' cursor.updateRow(row)...


0

I found an answer that worked. I was unaware of the format that the vertices tool used so was inputting the wrong input format, it is not dd*-2 but SHAPE. For anyone new to these tools like me here is what I found: NOTE: make sure that you do not have any programs open that are using the geodatabase you are working in or you will get a schema lock error. The ...


0

If you want to run small amounts of python code as part of a workflow WITHIN an existing model you would typically use the model only Calculate Value tool.


0

Most Toolboxes have an alias option. Sometimes this helps. Check the properties of the toolbox and set an alias (use a simple code or subject abbreviation). When calling the tool reference the alias. arcpy.ImportToolbox(r'..............\Generic_Tools.tbx') arcpy.MyTool_alias(var1, var2)


1

You can use Describe: import arcpy rasterfile = r"C:\folder\photo.tif" d = arcpy.Describe(rasterfile) ext = d.extent <Extent object at 0x1fc6aea9708[0x1fc302a0f30]>


2

As commented by @user2856 using a where_clause on your UpdateCursor is all that is needed. If you have variables fc, fld and val set to a feature class, a field name in that feature class, and a value in a text field respectively then this should work to change the value to a new value of "X": with arcpy.da.UpdateCursor(fc,fld,"{0} = '{1}'&...


3

Try changing this line: folderWorkspace = "C/Users/jessi/Desktop/CPSUGeog485/Lesson2" To this: folderWorkspace = "C:/Users/jessi/Desktop/CPSUGeog485/Lesson2"


2

You just need to make sure to read the values from each row in the desired order. Try this: fields = arcpy.ListFields(fc3) aliases = {field.name: field.aliasName for field in fields} fieldsToKeep =['REPORTER','RECOWNER','SCINAME','COMNAME','RECBASIS','GlobalID','OCCSTATUS','MANAGESTAT', 'POPSTAT','OBSDATE','COUNTRY','STATE','COUNTY','...


3

The documentation for the 'field' class explains that the .aliasName attribute holds the value of the field alias. So change the field_names = line to this: field_names = [field.aliasName for field in fields if field.name in fieldsToKeep] Or if you want to be a bit clearer, change it to this: field_aliases = [field.aliasName for field in ...


2

You are making a LAYER object using the tool MakeLasDatasetLayer() you are not making a DATASET. So change this line: arcpy.conversion.LasDatasetToRaster(r"C:\Tool\DSM_Processing\Pointcloud_Data\Pointcloud_LasDatasetLayer", r"C:\Tool\DSM_Processing\Pointcloud_Data\Pointcloud.tif","ELEVATION", "BINNING AVERAGE LINEAR", &...


2

I submitted this as an idea and apparently it can be done in ArcPy for ArcGIS Pro using the Cartographic Information Model: https://community.esri.com/t5/python-ideas/ability-to-access-the-popup-object-in-arcpy-arcgis-pro/idc-p/1042108#M32 The code snippet provided was as follows: p = arcpy.mp.ArcGISProject('current') m = p.listMaps('Map')[0] l = m....


Top 50 recent answers are included