Rounding the elements of a Python array (numarray module)

Chris P. chris.peressotti at utoronto.ca
Tue Nov 30 11:57:59 EST 2004


Hi.  I have a very simple task to perform and I'm having a hard time
doing it.

Given an array called 'x' (created using the numarray library), is
there a single command that rounds each of its elements to the nearest
integer?  I've already tried something like
>>> x_rounded = x.astype(numarray.Int)
but that only truncates each element (i.e. '5.9' becomes '5').

I've read over all the relevant numarray documentation, and it
mentions a bunch of Ufuncs that are available - there's 'floor' and
'ceil', but no 'round'.  And when I try using the built-in function
'round' on an array like so
>>> x_rounded = round(x)
I get "TypeError: Only rank-0 numarray can be cast to floats."

So I created a bad function that uses nested loops, but my arrays are
600x600x3 elements (I'm doing some image processing after converting a
PIL Image to a numarray array) and it takes a REALLY long time.  Has
anyone else had to do this, or knows of any tricks?  Any help is
appreciated.

- Chris

P.S. Here's my "bad function"

# This code assumes that 'the_array' is a 3-dimensional array.
def ArrayRound(the_array):
    result = numarray.zeros(the_array.shape)
    if len(the_array.shape) == 3:
        (depths,rows,columns) = the_array.shape
        for depth in range(depths):
            for row in range(rows):
                for column in range(columns):
                    result[depth][row][column] = #continued
                        round(the_array[depth][row][column])
    return result



More information about the Python-list mailing list