Rounding the elements of a Python array (numarray module)

From: Chris P. (chris.peressotti_at_utoronto.ca)
Date: 11/30/04


Date: 30 Nov 2004 08:57:59 -0800

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



Relevant Pages

  • ANN: numarray-0.8 released
    ... Numarray is an array processing package designed to efficiently ... Peter Verveer's nd_image package! ... Numarray now features a port of Paul Dubois Masked Array package, MA, ... 839377 Assigning a Numeric slice to a numarray array fails ...
    (comp.lang.python)
  • ANN: numarray-0.9
    ... Numarray is an array processing package designed to efficiently ... Numeric and features c-code generated from python template scripts, ... Decreased Ufunc overhead ...
    (comp.lang.python)
  • Re: permuting letters and fairy tales
    ... that the intetior letters are not even close to being in random order. ... maybe we can use numarray to a greater advantage. ... But could we find the word boundaries that ... It's a boolean-valued array. ...
    (comp.lang.python)
  • Re: arrays
    ... convenient to access it in C, without using numarray or Numeric. ... in a single list, rather than a list of lists, it is convenient to ... or a smaller multidimensional array if so. ...
    (comp.lang.python)
  • Re: NumPy (numarray) problem with C code
    ... I think I was using the wrong documentation. ... > You're using numarray, so you may want to use the numarray interface ... > instead of the Numeric compability interface. ... > and use NA_InputArray() to get the array. ...
    (comp.lang.python)