looping in array vs looping in a dic

Ian Kelly ian.g.kelly at gmail.com
Thu Sep 20 15:28:12 EDT 2012


On Thu, Sep 20, 2012 at 1:09 PM, MRAB <python at mrabarnett.plus.com> wrote:
> for col in range(cols):
>     for row in range(rows):
>         cat = valuesCategory[row, col]
>         ras = valuesRaster[row, col]
>         totals[cat] += ras

Expanding on what MRAB wrote, since you probably have far fewer
categories than pixels, you may be able to take better advantage of
numpy's vectorized operations (which are pretty much the whole point
of using numpy in the first place) by looping over the categories
instead:

for cat in categories:
    totals[cat] += np.sum(valuesCategory * (valuesRaster == cat))



More information about the Python-list mailing list