[SciPy-User] Picking a random element of an array with conditions
Keith Goodman
kwgoodman at gmail.com
Fri Jun 11 14:32:20 EDT 2010
On Fri, Jun 11, 2010 at 11:29 AM, Keith Goodman <kwgoodman at gmail.com> wrote:
> On Fri, Jun 11, 2010 at 11:21 AM, Keith Goodman <kwgoodman at gmail.com> wrote:
>> 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
>
> And here's the nd case:
>
>>> a = np.random.rand(10,10)
>>> idx = np.where(a.flat > 0.5)[0]
>>> a.flat[idx[np.random.randint(idx.size)]]
> 0.6073571170281532
Oh, I guess np.where is slow. So I'd just do it the easy and faster
way (second method below):
>> a = np.random.rand(10000)
>> timeit idx = np.where(a > 0.5)[0]; a[np.random.randint(idx.size)]
10000 loops, best of 3: 168 us per loop
>> timeit b = a[a > 0.5]; b[np.random.randint(b.size)]
10000 loops, best of 3: 119 us per loop
Sorry for all the mail.
More information about the SciPy-User
mailing list