More

Select random rows with python in arcgis

Select random rows with python in arcgis


I am new to using Python in ArcGIS, and I wonder: how do I select random lines (or every two lines) of an attribute table? I must select these lines and calculate them, so they are different from other.

I actually have some conditions. For example: I will have to calculate the area of a polygon and the area is less than 30 for example, I have to select one random point within that polygon and calculate his column so that it is different the other.

Part of calculating the area is already ready, lacking only get select random points.


Here's some code for creating a layer (named "lines_layer") with half of the rows randomly selected, which will work with ArcGIS 10.1+:

import arcpy import random fc = r'C:path	ofeatures.shp' # Path to feature class with attribute table to modify object_ids = [r[0] for r in arcpy.da.SearchCursor(fc, ['[email protected]'])] sample_size = len(object_ids) / 2 # To select more or fewer than half, change denominator random_ids = random.sample(object_ids, sample_size) oid_field = arcpy.Describe(fc).OIDFieldName selection_query = '"{0}" IN ({1})'.format(oid_field, ','.join(random_ids)) arcpy.MakeFeatureLayer_management(fc, "fc_layer", selection_query)

Just change thefcdefinition to point to the full path of the feature class or shapefile whose fields you want to calculate. (A layer name would work also, if you've already made a feature layer from it. In that case, half of the features in the layer would be selected.)

In your question, it sounds like selecting every other line may be good enough, in which case I would direct you to the query used in my answer to this question.


Watch the video: How to Create a Random Sample in Excel in 3 minutes!