Numeric help!

Carl Banks invalidemail at aerojockey.com
Wed Jun 28 20:21:08 EDT 2006


Sheldon wrote:
> Hi,
>
> I have the following loop that I think can be written to run faster in
> Numeric. I am currently using Numeric.
> range_va = [60,61,62,63,64,65,66,67,68,69,70,71,72]
> main.xsize= 600
> main.ysize= 600
> #msgva is an (600x600) Numeric array with mutiple occurrences of the
> values in range_va
> #sat_id is an (600x600) Numeric array with values ranging from -2 to 2
> for z in range_va:
>             count = 0
>             mbias = 0
>             for i in range(main.xsize):
>                 for j in range(main.ysize):
>                     if msgva[i,j] == z:
>                         mbias += sat_id[i,j] # take the sum of the
> values
>                         count += 1 # count the occurrences
>             tmp_array[0,index] = round(mbias/count,1) # store the mean
>             tmp_array[1,index] = z
>             index += 1
>
> Any help would be greatly appreciated!

I'm not sufficiently sure this isn't a homework problem, so here's a
partial answer.

Your intuition is correct--there's almost always a faster way to do it
when you're cycling through Numeric array indices in a Python for loop.
 Numeric and successors exist mostly to get rid of them.

Given z, you can calculate mbias in one line:

    mbias = Numeric.sum(
            Numeric.ravel(Numeric.where(msgva==z,sat_id,0)))

Here, the Numeric.where function allows you to filter out entries: it
returns an array with the elements of sat_id, but only  where the
corresponding element of msvga==z; otherwise the entry is zero.
Numeric.ravel flattens an multidimensional array into one dimension,
and, of course, Numeric.sum adds up all the elements in the array.

How to get count and to work this into your loop are left as an
exercise.


Carl Banks




More information about the Python-list mailing list