3

How to count the number of records from a field 'COVER' that is neither 'woods' and neither 'orchards'?

fileName = 'C:/gispy/data/ch17/parkCopy3.shp'
fields = ['COVER', 'FID']

count = 0 .

try:

with arcpy.da.UpdateCursor(fileName, fields) as cursor:
    for row in cursor:
        if row[0] != 'woods' or row[0] != 'orchards':
            count = row[0].count
            cursor.updateRow(row)

    del cursor
print 'Number of records with other cover types:{0}'.format(count)

except:

2
  • 1
    What's the error you faced with in python ? The code in the question is not complete. Also has syntax error "." after count = 0
    – BBG_GIS
    Commented Nov 16, 2017 at 14:31
  • I don't face any error, i just don't know how to handle the count for the other records that are not woods and orchards.
    – DDragos
    Commented Nov 16, 2017 at 14:39

3 Answers 3

3
import arcpy
arcpy.env.workspace = "C:/gispy/data/ch17"
fileName = 'parkCopy3.shp'
fields = ['COVER', 'FID']
myList = ['woods', 'orchards']
count = 0
with arcpy.da.SearchCursor(fileName, fields) as cursor:
    for row in cursor:
        if row[0] not in myList:
            count += 1

print 'Number of records with other cover types:{0}'.format(count)
  1. Don't forget to import arcpy at the beginning of the code.
  2. Use List to iterate the values (Cover and orchards)
  3. If you want just search and print the result, Use SearchCursor. You don't need to use UpdateCursor.
  4. I removed try- except because your code was not complete. Maybe you don't need to use try-except in your code.
1
  • 1
    and here's the obligatory plug for list comprehension :) count = len([i for i in arcpy.da.SearchCursor(fileName,fields) if not i[0] in myList])
    – mr.adam
    Commented Nov 16, 2017 at 15:20
3

You don't need a cursor to do that, GetCount() returns what you want. If you're using a database instead of a shapefile, this approach will probably be faster too.

arcpy.MakeFeatureLayer_management("C:/gispy/data/ch17/parkCopy3.shp", "selection", "COVER not in ('woods', 'orchards')")
print arcpy.GetCount_management("selection").getOutput(0)

For Desktop: http://desktop.arcgis.com/en/arcmap/latest/tools/data-management-toolbox/get-count.htm

For Pro: http://pro.arcgis.com/en/pro-app/tool-reference/data-management/get-count.htm

1
  • The question says nothing about either Pro or Desktop, so I assume either is correct. I'll include a link to the Desktop documentation too, although it's identical to Pro.
    – Berend
    Commented Nov 20, 2017 at 11:28
1

An alternative approach is to select the rows you want to count and then run the summary statistics tool. These could be called from a python script or knocked together using model builder in half the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.