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

Keith Goodman kwgoodman@gmail....
Fri Jun 11 13:16:26 CDT 2010


On Fri, Jun 11, 2010 at 11:12 AM, 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))]]

How about:

>> a = np.random.rand(10)
>> idx = a > 0.5
>> a[idx[np.random.randint(10)]]
   0.58803647603961251


More information about the SciPy-User mailing list