summing NumPy byte arrays

Chris Barker chrishbarker at home.net
Fri Nov 30 15:25:36 EST 2001


"David R. Smith" wrote:
> 
> I have a big NumPy byte array, and want to sum it.  Unfortunately, the
> add.reduce (alias: sum) method does the sum in the same size receptacle,
> e.g.,
> 
> >>> from Numeric import *
> >>> X = arange(255, typecode='b')
> >>> sum(X)
> 129
> How can I get it to sum the array in a full-width accumulator, without
> making an up-sized copy of the array?

I'm pretty sure you can't. That would take some preety fancy footwork in
the typecasting code.

> ps. The array I am working with is a 2-d noncontinguous slice.

Your options are to either upcast the whole thing (you can make a copy
of that slice, and only upcast the copy),

>>> from Numeric import *
>>> X = arange(216, typecode='b')
>>> X.shape = (6,6,6)
>>> s = sum(X[3,:,:].copy().astype(Int))
>>> s
array([738, 744, 750, 756, 762, 768])

Or to write a little C routine, which would be pretty straightforward if
you only need it to work for one type, and one rank.

-Chris

-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list