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

Keith Goodman kwgoodman at gmail.com
Fri Jun 11 14:21:02 EDT 2010


On Fri, Jun 11, 2010 at 11:16 AM, Keith Goodman <kwgoodman at gmail.com> wrote:
> On Fri, Jun 11, 2010 at 11:12 AM, R. Padraic Springuel
> <R.Springuel at 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

Oh, sorry, that doesn't work since idx is bool. How about:

>> a = np.random.rand(10)
>> idx = np.where(a > 0.5)[0]
>> a[idx[np.random.randint(idx.size)]]
   0.94308730304099841



More information about the SciPy-User mailing list