HOW TO

Select every other 'n' rows in a table in ArcMap

Last Published: April 25, 2020

Summary

In some instances, users may want to select every other 'n' rows in a table to edit the selected features without having to select and populate the rows individually. This article demonstrates how to select every other 'n' rows using a Python script. In this example, the interval value is set to 3. A new layer with both selected and unselected features is created as the resulting output. In the attribute table for the new layer, three rows are selected, the next three rows are skipped and the same process is repeated until the end of all rows.

The result of this process is that half of the rows are selected from the original table, but these selections are specified as every other three rows. The following image shows the expected output:

An image of the new layer with selected attributes created after running the Python script.
 

Procedure

The following Python script iterates through ObjectIDs and selects every other 'n' rows according to the set interval value using the Select Layer By Attribute tool and the Make Feature Layer tool. Changing the interval value in the script changes the number of rows selected and skipped. Follow the instructions below to run the script in the Python window.
  1. On the ArcMap main menu, click Geoprocessing > Python to open the Python window.
  2. Copy and paste the script in the Python window.
import arcpy
 
##Replace data path## 
fc = r'C:\EsriTraining\SpatialProb\CraterLake.gdb\Roads'

##Set desired interval. interval = 1 selects every other row, interval = 2 selects 2, skips 2,##
##interval = 3 selects 3, skips 3 and so on.## 
interval = 3
selected_oid = []
ready_to_add = False
interval = abs(interval)
 
##Replace layer_name if desired##
fc = arcpy.MakeFeatureLayer_management(fc, "layer_name")
 
with arcpy.da.SearchCursor(fc, 'OID@') as cur:
     for i, row in enumerate(cur):
         if i % interval ==0:
             ready_to_add = not ready_to_add
         if ready_to_add:
             selected_oid.append(unicode(row[0]))
             
where = 'OBJECTID in ({})'.format(', '.join(selected_oid))
selected_fc = arcpy.SelectLayerByAttribute_management(fc, "NEW_SELECTION", where)
  1. Replace the source path of the feature layer and the new layer name.
  2. Press Enter.

Article ID:000015978

Software:
  • ArcMap

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Related Information

Discover more on this topic