Quantcast
Channel: Question and Answer » arcpy
Viewing all 767 articles
Browse latest View live

Error 000728 field does not exist within table – field already exists

$
0
0

I am running arcpy.AddField_management to add a field called “cnid” and update it with x centroid values.
For add.field I get the error “cnid” already exists. I tried print.field name and I cannot see “cnid” field. Now I am running calculate shape centroid and I get the error message “cnid” does not exist within table. I cannot understand, sometimes it works (if I close arcmap and open it again) but if I run both codes, add field and update it, it doesnt work.

    # AddField for new fields 
arcpy.AddField_management("Connections","cnid","DOUBLE", "", "", "", "", "NULLABLE")

    #test fields
    for field in arcpy.ListFields ("Connections"):
    ...     print field.name

    xExpression = "float(!SHAPE.CENTROID!.split()[0])" 
    inFeatures ="Connections"
    fieldName ="cnid"
    arcpy.CalculateField_management ("Connections","cnid",xExpression, "PYTHON")

I read something about in_memory and refresh bug from Why am I getting an ERROR 000728: Field *fieldname* does not exist within table even though field exists?, but how can I refresh it without having to close and open it again? I am using ArcMap’s Python window. Any help would be very much appreciated.


Finding duplicate records in field using ArcGIS for Desktop?

$
0
0

im looking for duplicate records in dbf files based upon the attribute called ‘ID’. I have various dbf files from 500,000 records to 1.5 million and I know there are a host of duplicates.

I would like to add a field ‘Duplicate’ that says Yes or No (or 1 or 0 is fine) when the ID attribute is present elsewhere. Using the following python script in Field Calculator returns 1 for a duplicate entry and 0 for unique entry;

uniqueList = []
def isDuplicate(inValue):
  if inValue in uniqueList:
    return 1
  else:
    uniqueList.append(inValue)
    return 0
isDuplicate(!FIELD_NAME!)

however the 1st record of, for example, 5 duplicate IDs will also be returned as a 0 (the subsequent 4 are considered the duplicates). I would need all 5 to be marked as duplicate as the ID exists elsewhere.

Using the following code will give you an incremental count of how many times that ID occurs with 1 meaning the 1st occasion and so forth;

UniqueDict = {}
def isDuplicateIndex(inValue):
    UniqueDict.setdefault(inValue,0)
    UniqueDict[inValue] += 1
    return UniqueDict[inValue]

isDuplicateIndex( !YOUR_FIELD! )

I just want a 1 (or Yes) if the ID of that record exists elsewhere! (ArcGIS version 10.1)

I have seen other answers such as Python script for identifying duplicate records (follow up) but it doesn’t quite work.

How to check out arcgis 10.2 desktop license using arcpy?

$
0
0

Referring to ArcGIS help it seems possible to check out advanced desktop license. But typing
arcpy.CheckOutExtension('ArcInfo')

gives

Unrecognized extension code ArcInfo

Assign point IDs to respective start and end attributes of a polyline

$
0
0

I have two shapefiles, Point and Polyline. I’m trying to populate my polyline layer with the point data ID (systemID) where the lines start to where they end; eg. create two columns (from and to). The lines already have flow direction assigned to them. I am using ArcHydro tools but Arcpy is also fine.

In ArcHydro I have tried using Attribute Tools > Generate From/To Nodes for lines but it creates values for To and From that are not from my point data. My other alternative was using Feature to Vertices and joining the result to my point data table to get the systemID. But then I would have to update the polyline layer as well. I am sure there is a easier way of doing it.

Note: not all the lines have points at the vertices, blank values are fine for them.

MakeFeatureLayer_management wrong output

$
0
0

I have a huge database with Sightings from whales and dolphins from 1995 till today.
So I want to sort the database with python.

Till now I can make FeatureLayers for each year

for year in range(1995,2014):
arcpy.MakeFeatureLayer_management
(“Sightings95-14″, “test%s” % year, “DATE >= date’01.01.%s’ AND DATE < date’01.01.%s’” % (year, year+1))

now I want to sort it into each month (no matter of the yaer), because there are way more sightings in may than in december for example.

If I excecut this code:

for month in range (01,12):
arcpy.MakeFeatureLayer_management
(“Sightings95-14″, “test%s” % month, “DATE >= date’01.%s.1995′ AND DATE < date’31.%s.2014′” % (month, month+1))

it makes the 12 FeatureLayers but in each Layer is the hole database included so he did not “sort” it right.

What is my mistake ?

arcpy cursor not accepting float(Inf)

$
0
0

I have a vector layer in which I have added some fields of type ‘float’ using arcpy.AddField_management. I’m performing simple calculations between those fields using update cursors but the problem is that when I divide the values by 0, I get a run-time error even though I’m using Inf with the float function.

This is my code:

with arcpy.da.UpdateCursor('flurstcuke_cropped5', ['FID','totresgeb', 'totresgbpt','difresarea','scaledif']) as cursor6:

for row6 in cursor6:

   row6[3] = row6[2] - row6[1]

   try: 

       row6[4] = ((row6[2] - row6[1])/row6[1]) * 100

   except ZeroDivisionError:

      row6[4] = float('INF')


   cursor6.updateRow([row6[0], row6[1], row6[2], row6[3], row6[4]])

The message I get is that ‘the value type is incompatible with the field type. [scaledif].’ And I know it’s referring to Inf since I have also set up a counter in my script to determine where the program is. But I don’t understand that since ‘Inf’ is a floating number here and the field’s type is also float

How to get a search cursor on a particular version in arcpy

$
0
0

I have a versioned database in ArcGIS and I am wondering how can I tell arcpy what version to query. The closest I have got to an answer has been building a particular connection file that specifies the version to connect to, or use ChangeVersion_management which only works on layers and views.

I can easily do that in a published map on the web using ArcGIS JS API by setting the version using layer.setGDBVersion(version)

ArcGIS 10.1 – Error No spatial reference exists

$
0
0

I’m encountering a new error on some geoprocessing. It originally showed up while running commands in arcpy but now it crops up whenever I run some tools. I’ve been using the Extract by Mask on some rasters, and then using the Focal Statistics function on the resulting clipped grid. The main error that’s showing up is:

ERROR 999999: Error executing function
Unexpected operation
No spatial reference exists

A screen grab of the error messages is attached. The other two errors (010302 and 010067 ) have no helpful information. I’ve been running similar processes for months and haven’t encountered this before. Both the input layers (a raster and polygon feature) are in WGS84 with their coordinate system defined. Both of these input layers are in a File GDB and I did export them to a shapefile and GRID and the process executed successfully. I could run this series of processes outside of the GDB but it’d be nice not to.

Any thoughts on why this is happening?error message


Issues Adding MapServerCache Raster Layers to Mxd

$
0
0

I have created a data consolidation tool. It consolidates a users mxd’s vector and raster data into a project structure. It also allows the user to optionally cache our companies ArcGIS Server Web Maps. The arcpy.gp.ExportMapServerCache produces a compact cache dataset, which is turned into a layer with arcpy.MakeRasterLayer_management and added to an mxd with arcpy.mapping.AddLayer.

The layer is successfully added to the mxd. But it’s not the same as when the user does it manually. The arcpy layers “data source” is not the one that was dictated to it, rather it references a temp in the users application data folder instead.

Why does it reference a temp, and NOT the actual raster cache?

### MOVE CONSOLIDATED MXD TO PROJECT CORE LEVELS
MasterMxdPath = UserProjectPath+"\Extract_"+Project_Name+".mxd" #new mxd name
mxd2Name = UserProjectPathGDB+"\v101\"+mxdNAME #get consolidated mxd
mxd2 = arcpy.mapping.MapDocument(mxd2Name)
mxd2.saveACopy(MasterMxdPath, "10.1")
del mxd2

### ADDING WEB CACHE TO MXD
try:
    UserProjectPathCache = UserProjectPath+"\Cache"
    arcpy.env.workspace = UserProjectPathCache
    RastersL = arcpy.ListRasters("*", "ALL")
    RcCount = len(RastersL)

    if RcCount >0: ### If there's a web cache:
        arcpy.AddMessage("    J: Web Cache Exists:")
        arcpy.AddMessage("    J: There are: " +str(RcCount) +" rasters")

        ### Get Dataframe From MXD
        mxd3 = arcpy.mapping.MapDocument(MasterMxdPath)
        df = arcpy.mapping.ListDataFrames(mxd3)[0]

        ### Turn Rasters Into Layers & Add To Dataframe
        CNTR = 0
        for raster in RastersL:
            arcpy.AddMessage("    J: Cache Name: "+str(raster))
            CNTR = CNTR + 1
            RasterLayerName = "WebServiceCache_"+str(CNTR)          
            RasterPath = UserProjectPathCache+"\"+raster
            arcpy.AddMessage("    J: New Layer Name: "+ RasterLayerName)
            RLayer = arcpy.MakeRasterLayer_management(RasterPath,RasterLayerName)
            layer = RLayer.getOutput(0)
            arcpy.mapping.AddLayer(df, layer, 'Bottom')
            mxd3.save()
            arcpy.AddMessage("    J: Mxd Saved With Cache Layer")
            del RLayer, layer, df
        del mxd3

        ### Remove Webservices From Dataframes in MXD
        mxd4 = arcpy.mapping.MapDocument(MasterMxdPath)
        df2 = arcpy.mapping.ListDataFrames(mxd4)[0]

        for lyr2 in arcpy.mapping.ListLayers(mxd4, "", df2):
            if lyr2.supports("SERVICEPROPERTIES"):
                servProp2 = lyr2.serviceProperties
                if lyr2.serviceProperties["ServiceType"] != "SDE":
                    arcpy.AddMessage("    J: Removing WEB SERVICE LAYER: " + lyr.name)
                    arcpy.mapping.RemoveLayer(df2, lyr2)
        mxd4.save()
        arcpy.AddMessage("    J: Final Mxd Saved: ")
        del mxd4

    else: ### If there's no web cache
        arcpy.AddMessage("J: No Web Cache Exists:")

except Exception as e:
    arcpy.AddError(e.message)
    arcpy.AddMessage(" DID NOT ADD RASTER TO MXD")

Image Showing Layer Paths

Calculating centroid latitude in ArcMap throws error in Arcpy

$
0
0

I can create a centroid latitude field in ArcMap10.1 using “Calculate Geometry…” in the attribute table, but when I try the same thing using:
arcpy.CalculateField_management(bins_WGS84, “cent_lat”, “!SHAPE.CENTROID.Y!”, “PYTHON_9.3″),

I get the following error: arcgisscripting.ExecuteError: ERROR 000539: Error running expression: GPVARIANTOBJECT0.CENTROID.Y. It only happens occasionally, but kills my script and costs me lots of time/data. On the particular dataset I’m testing, it happens about 10 rows in, although the geometry looks fine and Arcmap doesn’t complain when finding the centroid. Any help is greatly appreciated.

I know it is possible, because it’s working for the same dataset in ArcMap, however, this action does not show up in the Results window.

python shell crashes on table to table conversion

$
0
0

I have two computers running the same code and on one (with better performace) it runs fine but the other crashes the python shell when executing the code below. I really don’t understand why, any ideas?

def csv_to_table():
    """
        Function: csv_to_table
        ----------------------
        Convert CSV file to geo database table.
    """
    try:           
        # convert and save csv to file geo database
        arcpy.TableToTable_conversion(
            config['arcgis']['csv'],
            config['arcgis']['gdb'],
            config['arcgis']['table']
        )
    except arcpy.ExecuteError as e:
        print e
        message.error("Unable to convert CSV to Table.")

Update:
Both computers are running:
Python 2.7.2
ArcMap 10.1

Python loop doesnt work properly for hundreds of Raster files (HDF)!

$
0
0

For generating Time Series, I prepared a python script which are supposed to get all task done through looping.

Interestingly, It stops working after 12 HDF file but I need to do loop through all HDF files on my disk.

What do I can do?

Batch arcpy.CopyRaster after arcpy.ASCIItoRaster

$
0
0

I’m new to arcpy and am having trouble running CopyRaster. Do I need a separate for loop for this process like I have below?

import os,arcpy, glob  


filepath = r"C:VMsharedsmall_example_valley2snowdepthtest"   

outFolder = r"C:VMsharedsmall_example_valley2snowdepthout"  


ascList = glob.glob(filepath + "/*.asc")  

print ascList  

rasterpath = r"C:VMsharedsmall_example_valley2snowdepthout"

LastOutFolder = r"C:VMsharedsmall_example_valley2snowrast"

rasterList = glob.glob(rasterpath + "/*.tif")
print rasterList


for ascFile in ascList:  

    outRaster = outFolder + "/" + os.path.split(ascFile)[1][:-3] + "tif"  
    print outRaster  

    arcpy.ASCIIToRaster_conversion(ascFile, outRaster, "FLOAT")



for rasterFile in rasterList:   

    LastOutRaster = LastOutFolder + "/" + os.path.split(rasterFile)[1][:-3] + "tif"
    arcpy.CopyRaster_management(r"C:VMsharedsmall_example_valley2snowdepthout",r"C:VMsharedsmall_example_valley2snowrast","DEFAULTS","","","NONE","NONE","16_BIT_UNSIGNED")

Edit:

After modifying the script, I get the following error:

ERROR 000876: Output raster:
C:VMsharedsmall_example_valley2snowdepthtestsnowdepthN0001.asc’s
extension is invalid for the output raster format.

import os,arcpy, glob

filepath = r"C:VMsharedsmall_example_valley2snowdepthtest"
outFolder = r"C:VMsharedsmall_example_valley2snowdepthout"
ascList = glob.glob(filepath + "/*.asc")

rasterpath = r"C:VMsharedsmall_example_valley2snowdepthout"

OutFolderTwo = r"C:VMsharedsmall_example_valley2snowrast"

rasterList = glob.glob(rasterpath + "/*.asc")
print rasterList

for ascFile in ascList:
    outRaster = os.path.join(outFolder, ascFile)
    arcpy.ASCIIToRaster_conversion(ascFile, outRaster, "FLOAT")

rasterList = glob.glob(outFolder + "/*.tif")

for rasterFile in rasterList:

    OutRasterTwo = os.path.join(OutFolderTwo, rasterFile)
    arcpy.CopyRaster_management(rasterFile, OutRasterTwo, "DEFAULTS","","","NONE","NONE","16_BIT_UNSIGNED")

Is it possible to toggle draft mode in ArcGIS with Python?

$
0
0

I’m curious if it is possible to toggle on and off ‘draft mode’ in layout view in ArcGIS using python scripting. Does anyone have any ideas?
Python is preferred, but if there is another solution in a different language it would also be beneficial!

Trying to loop if condition at PYTHON code using Arcpy

$
0
0

I’m working with Arcgis 10.1, i’m trying to loop if condition on PYTHON code, but they give me as error : Parsing error IndentationError: unexpected indent (line 18)
I don’t know what is going wrong.
This is the code, any help would be appreciated.

import arcpy
import math
arcpy.AddField_management("Parcelles_class_FeatureToPoi3","new_field","DOUBLE")
cur = arcpy.UpdateCursor("Parcelles_class_FeatureToPoi3") 
    for row in cur:
...     PointX = row.getValue("POINT_X")
...     print PointX
...     PointY = row.getValue("POINT_Y")
...     print PointY
...     EndX = row.getValue("end_x")
...     print EndX
...     EndY = row.getValue("end_y")
...     print EndY
...     dx = EndX - PointX 
...     dy = EndY - PointY 
...     azimuth = math.atan2(dy, dx)
...     print azimuth
...     azimuth_gr = azimuth*200/3.14519
...     print azimuth_gr

    if (dy>=0 and dx>= 0 ):
...     azimuth_fi = azimuth_gr
...     else : 
...         if (dy>=0 and dx<= 0 ):
...             azimuth_fi = 200- azimuth_gr
...             else :
...                 if (dy<=0 and dx<= 0 ):
...                     azimuth_fi = 200 + azimuth_gr
...                     else :
...                         if (dy<=0 and dx>= 0 ):
...                             azimuth_fi = 400 - azimuth_gr
...                             print azimuth_fi

    row.setValue("new_field", azimuth_fi)
    cur.updateRow(row)

limit spatial extent of arcpy cursor

$
0
0

How do I limit spatial extent of features that is returned by arcpy.da.SearchCursor? Can I use arcpy.env.extent? Or somehow come up with sql statement to specify spatial relationship? Or do I have to arcpy.SelectLayerByLocation_management to do intersection of my area of interest.

EDIT:
Here is what I want to accomplish. Want to visit features from a feature class within a set extent. I was hoping that second use of arcpy.da.SearchCursor respects arcpy.env.extent, but apparently it ignores it.

How can I do this (visit spatial subset of features)? I want to have method with decent efficiency (e.g. avoid copying of features).

import arcpy
def proc():

    # I/O files
    fo = open('c:/users/yosuke/documents/log.txt','w')
    fc = arcpy.CopyFeatures_management('c:/Users/Yosuke/documents/ArcGIS/polytical_boundaries.mdb/tl_2010_us_state10', r'in_memoryfc')

    # grab everything, works fine
    arcpy.env.extent = 'MAXOF'
    n = int(arcpy.GetCount_management(fc).getOutput(0))
    m = len(list(arcpy.da.SearchCursor(fc, ('SHAPE@',))))
    extent = arcpy.Describe(fc).extent
    # got 52 from both, as expected
    fo.write('n: %sn' % n)
    fo.write('m: %sn' % m)
    fo.write('extent: %sn' % extent)
    fo.write('n')

    # want to grab only western USA
    arcpy.env.extent = arcpy.Extent(-120, 0, -90, 80)
    # this counts 27 western states, I suppose.
    n = int(arcpy.GetCount_management(fc).getOutput(0))
    # this still marches through all states, I want this to be spatial subset of USA
    m = len(list(arcpy.da.SearchCursor(fc, ('SHAPE@',)))) 
    extent = arcpy.Describe(fc).extent
    fo.write('n: %sn' % n)
    fo.write('m: %sn' % m)
    fo.write('extent: %sn' % extent)
    fo.write('n')

    # For now I am making copy of feature class
    # turned out that this is not very bad for my application, other processing
    # tasks I am applying on cursor rows are more computationally expensive.
    # I still want to know if this is standard way to accomplish this kind of
    # tasks (subset cursor by extent)
    fc2 = arcpy.CopyFeatures_management(r'in_memoryfc', r'in_memoryfc2')
    n = int(arcpy.GetCount_management(fc2).getOutput(0))
    m = len(list(arcpy.da.SearchCursor(fc2, ('SHAPE@',))))
    extent = arcpy.Describe(fc2).extent
    fo.write('n: %sn' % n)
    fo.write('m: %sn' % m)
    fo.write('extent: %sn' % extent)
    fo.write('n')

How to get information about layers using Arcpy

$
0
0

I have this layer structure in ArcMap:

enter image description here

“Localities, Gazeteers, Bases, Regions, and Territorial Claims are all Group Layers. All others under these are layers. I have a script that uses the Arcpy Describe method to go under each layer and get its full directory path. Here is the script:

import arcpy
mxd=arcpy.mapping.MapDocument("CURRENT")
dataframes=arcpy.mapping.ListDataFrames(mxd)
for dataframe in dataframes:
    for lyr in arcpy.mapping.ListLayers(mxd, "", dataframe):
        if not lyr.isGroupLayer:    
            print(arcpy.Describe(lyr).catalogPath)

This would return something like: C:/Folder/Subfolder/layer.shp
Now, I am trying to figure out a way to get the path of each layer relative to the map. For example, for layer "features_multipoint", I need the script to report something like this:

MapDocument/Localities/Gazeteers/features_multipoint

The Describe method seems to not provide such capabilities.

How to get an ArcGIS custom tool to run fom the command line?

$
0
0

I have been experimenting with ESRI’s CalculateArea custom tool and it works fine running within ArcGIS from a toolbox. Then I wanted to see if I could run it as a standalone script from the commandline like this:

c:Python27ArcGIS10.1python.exe calcAreaTest.py

calcAreaTest.py

import arcpy
arcpy.AddToolbox(r"D:Toolbox.tbx")
arcpy.CalculateArea(r"D:data.gdbdata", "Area")

The following error occurs:

Traceback (most recent call last):
  File "D:calcAreaTest.py", line 3, in <module>
    arcpy.CalculateArea(r"D:data.gdbdata", "Area")
  File "D:Toolbox.tbx", line 25, in CalculateArea
arcgisscripting.ExecuteError: ERROR 000582: Error occurred during execution.

I can paste the same code from calcAreaTest.py into the ArcGIS Python code window and it works. Anybody know how I can get it to work from the commandline?

Here is the link to the source code of the GPCalculateArea tool if anybody is interested at looking it.
GPCalculateArea custom tool

Change Privileges tool does not work against feature dataset containing a network dataset

$
0
0

I’m trying to change the privileges on a feature dataset that contains a topology and network dataset using the ChangePrivileges geoprocessing tool. This works if I run the command manually from the Python interpreter window in ArcCatalog or ArcMap. When I save this script and try to run it from Idle or PyScripter I get the following error message.

ExecuteError: ERROR 999999: Error executing function. Underlying DBMS
error [[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect
syntax near ‘-’.]

Here is my code:

import arcinfo
import arcpy

arcpy.ChangePrivileges_management(DatebaseConnection, "GISViewer", "GRANT", "")
arcpy.ChangePrivileges_management(DatebaseConnection, "GISEditor", "GRANT", "GRANT")

The script will work if I remove the network dataset from the feature dataset. Is this a known issue, or is there something I can change in the network dataset setup?

Use row as input to other processes in python

$
0
0

I am new to python and need help. Looked for my answer but don’t know if I am even using the correct terminology.

I have a model in which I iterated through rows and performed a set of processes on each. For example a feature class with 10 features and on each of the 10 features I wanted to create an individual feature class….or… for each row create a raster based on the field (e.g.) ID. I am trying to turn this to python due to a host of reasons.

I am using 10.1 and the error is ocuring at line 40 “FeatureClassToFeatureClass”
I believe that it is failing due to my improper use of ‘row” as the input.

Here is what I have so far, but I cannot get it to work


# Import arcpy module
print "Starting...."
import arcpy
from arcpy import env 

# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")
env.overwriteOutput = True

selectingfeatures = "\\silver\clients\trans1.shp"
Trans1_shp = "\\silver\clients\trans1.shp"
basecldem = "\\silver\clients\basecldem"
TEMP = "\\silver\clients\TEMP"
Zone3_shp = "\\silver\clients\Zone2.shp"
transarea = "\\silver\clients\transarea"
RegionGRP = "\\silver\clients\regiongrp"
ZonalMean = "\\silver\clients\zonalmean"
ZoneArea = "\\silver\clients\zonearea"
Transition__n_ = "\\silver\clients\transition_%n%"
I_trans1 = "I_trans1_FID"

selectingLayer = arcpy.MakeFeatureLayer_management(selectingfeatures)
rows = arcpy.SearchCursor(selectingLayer) 
#cursor = arcpy.SearchCursor(fc)
#row = cursor.next()
#while row:
#    print(row.getValue(field))
for row in rows:
    arcpy.FeatureClassToFeatureClass_conversion(row, TEMP, "Zone2.shp", "", "ID "ID" true true false 4 Short 0 4 ,First,#,\\silver\clients\Projects\P696\8_BaseMine\Processing\TEMP\trans1.shp,ID,-1,-1", "")
    print "Finished PFC 2 FC...."
# Process: Polygon to Raster
    arcpy.PolygonToRaster_conversion(Zone3_shp, "ID", ZoneArea, "CELL_CENTER", "NONE", "1")
    print "Finished Polygon to Raster...."
# Process: Extract by Mask
    arcpy.gp.ExtractByMask_sa(basecldem, Zone3_shp, transarea)
    print "Extract by Mask...."
# Process: Region Group
    arcpy.gp.RegionGroup_sa(ZoneArea, RegionGRP, "FOUR", "WITHIN", "ADD_LINK", "")
    print "Finished Region Group...."
# Process: Zonal Statistics
    arcpy.gp.ZonalStatistics_sa(RegionGRP, "VALUE", transarea, ZonalMean, "MEAN", "DATA")
    print "Finished Zonal Statistics...."
# Process: Raster Calculator
    arcpy.gp.RasterCalculator_sa("If( "%basecldem%" > ( 0.5 + "%ZonalMean%" ), 0, 1 )", Transition__n_)
    print "Finished Raster Calcualtor"
#row = cursor.next()
Viewing all 767 articles
Browse latest View live