[SciPy-User] Picking a random element of an array with conditions

Anne Archibald aarchiba@physics.mcgill...
Fri Jun 11 13:31:44 CDT 2010

On 11 June 2010 14:12, R. Padraic Springuel <R.Springuel@umit.maine.edu> wrote:
> I'd like to pick the random element of an array from those elements
> which meet a certain condition.  I.e. pick an element of a for which a
> == value is True.
> Without the condition, I'd phrase the command like this:
> a[random.randint(len(a))]
> Is there some similar thing that I can do to pick with the condition in
> an efficient manner?  So far all I've come up with involves looping over
> the array to construct an array of indecies so that I can write:
> a[indecies[random.randint(len(indecies))]]

If all you need is an element, then the easiest thing to do is pull
out those matching the condition:

b = a[a>3]
c = b[random.randint(len(b))]

(or a minor variation on this if a is not one-dimensional)

If you need the location in the original array of a random element
matching the condition, the easiest thing to do is build an index

ix = np.nonzero(a>3)

Now ix is a tuple of m index arrays if a is m-dimensional.

i = random.randint(len(ix[0]))
e = tuple(ia[i] for ia in ix)

Now e is a tuple pointing to a random element meeting the condition.

> --
> R. Padraic Springuel
> Research Assistant
> Department of Physics and Astronomy
> University of Maine
> Bennett 309
> Office Hours: By Appointment Only
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user

More information about the SciPy-User mailing list