3

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.

nmpeterson
8,42334 silver badges60 bronze badges
asked Sep 18, 2014 at 19:04
3
  • What are you having issues with? Have you tried anything? Please post code you are having trouble with so we can help you figure it out. Commented Sep 18, 2014 at 19:08
  • I tried many things, however none worked. What I have is a layer in arcgis called "Pontos_0_25" and need to randomly select rows that layer Commented Sep 18, 2014 at 19:12
  • How many rows do you need to select at random? Half? Commented Oct 6, 2014 at 14:01

1 Answer 1

3

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\to\features.shp' # Path to feature class with attribute table to modify
object_ids = [r[0] for r in arcpy.da.SearchCursor(fc, ['OID@'])]
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 the fc definition 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.

answered Oct 6, 2014 at 15:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.