2

Using the Field Calculator in ArcGIS for Desktop, I want to randomly choose one field from a list of 10 fields (strings).

The Excel equivalent, which is working, is: =INDEX(A2:J2;rnd()*10+1).

How can I do that in VBScript preferably (or in Python)?

2 Answers 2

1

Using Python as your parser, create a list of your fields and then use a random integer as an index to pull one out randomly.

enter image description here

Note 1: random module needs to be imported in the codeblock to ensure it's available.

Note 2: If you were to modify this for more or less field values, adjust the last number (shown as 9) to be the length of the list minus 1.

3
  • The random module is already imported in Field Calculator, so you don't need to use the code block at all. Very clever, +1!
    – Paul
    Nov 10, 2015 at 2:30
  • 1
    Thanks. I'm not sure that is correct about random being already imported, at least not by default. But if it is, doesn't hurt.
    – DWynne
    Nov 10, 2015 at 22:29
  • 1
    you are correct. Apparently I had randomly (heh) imported random in the Python window for something else and it carried over.
    – Paul
    Nov 10, 2015 at 22:34
0

I think simply this will do with VBScript, using your example of 10 fields to choose from by index (0-9):

int(10*rnd)

...and with a Python codeblock using numpy:

import numpy.random as R

def getRandom(numFlds):
     return int(R.random()*numFlds)

The above Python block would be called by (again using a 10 field example):

getRandom(10)

Extending this a little, let's say you wanted to use the random index generated to return the actual field names (instead of the index), then this is convenient using Python (uses the 1st layer in the default data frame):

import numpy.random as R
Flds = arcpy.ListFields(arcpy.mapping.ListLayers(arcpy.mapping.MapDocument('CURRENT'), '*')[0])
numFlds = len(Flds)

def getRandom():
     return Flds[int(R.random()*numFlds)].name

Of course, if you're calculating this in a 'draft' field appended to the end of the same table the calculation is based on, and you don't want to include this field in the random generator, then you can simply subtract the number of 'draft' fields from numFlds var before the def declaration, i.e., if just one text field is appended to the end of the table to hold this calculation (and is to be excluded), then numFlds = len(Flds) - 1 [instead of numFlds = len(Flds)].

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.