Is there a way to count the records in a feature layer?

4804
4
03-26-2012 01:03 PM
JohnPersley
New Contributor
I need to display several layers from the same feature class using definition queries for different systems and using the same template for different projects. While I have created a script that can automatically produce these layers in an MXD, the definition query will often reduce number of records to zero for certain systems, eliminating the need for it as a layer. I would like to use an IF statement with arcpy.mapping.RemoveLayer to automatically remove those layers that do not return results, but not sure which functions may be able to do this. I have looked into using SearchCursor but do not otherwise know how to identify the number of records in the attribute database for a particular layer.
Tags (2)
0 Kudos
4 Replies
MathewCoyle
Frequent Contributor
0 Kudos
StephenBarrow
New Contributor
Would arcpy.GetCount_management() help?
0 Kudos
JakeSkinner
Esri Esteemed Contributor

Hi John,

Matthew and Stephen suggestions are right on track.  Either using the Search Cursor, or the Get Count will be identical in performance.  Example using Search Cursor:

mxd = arcpy.mapping.MapDocument(r"C:\Projects\\Municipality.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
        list = []
        with arcpy.da.SearchCursor(lyr, ["OID@"], "OBJECTID > 0") as cursor:
                for row in cursor:
                        list.append(row[0])
        del cursor
        count = len(list)
        if count == 0:
          .....                     
del mxd

Example using Get Count:

mxd = arcpy.mapping.MapDocument(r"C:\Projects\Municipality.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]

for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
       result = arcpy.GetCount_management(lyr)
       count = int(result.getOutput(0))
       if count == 0:
         .....
del mxd
0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Both techniques will/do work, but in my experience the performance is not identical between the two.  For small to medium datasets (~100,000 records or less), the performance can be quite similar with the arcpy.da.SearchCursor and arcpy.GetCount_management.  For larger datasets, I have seen GetCount outperform cursors by 3 to 10 times.

Jason Scheirer​ speaks to why using a GP tool is faster than a Python cursor with larger datasets:  Re: How to determine number of records using arcpy.da.SearchCursor​.

0 Kudos