[Numpy-discussion] two tricky operations

Rick White rlw at stsci.edu
Thu May 2 11:59:18 EDT 2002

Since nobody else has replied to this yet, I'll take a crack at it.

On Thu, 2 May 2002, Pete Shinners wrote:

> help, i need help formatting some data in Numeric arrays. i can't quite
> seem to make it happen. here they come... (beware)
> 1: i want to create a simple 3d array, so that accessing it with any two
> indices gives me the same result as those two indices..
> 	myarray[1,2] == 1,2
> 	myarray[4,4] == 4,4
> i would assume this just involves mixing two arange()'s together, but i
> can't seem to get them meshed together correctly. actually, this is
> something i think i'd want quite a bit, it'd be real real nice if arange
> could take multiple axes. :]  i thought this might be a good
> "fromfunction" situation, but i couldn't get that to go either.

This works.  I don't know whether it is optimal, though I think it
isn't bad.  Note that the returned values are 2-element Numeric arrays,
not tuples.  Seems to me that arrays are a lot more usable as return

def twod(n,m):
    a = zeros((n,m,2))
    b = arange(n*m)
    a[:,:,0] = transpose(reshape(b % n, (m,n)))
    a[:,:,1] = reshape(b % m, (n,m))
    return a

> 2: i have a 3d array with image data (RGBs). i want to flatten only the
> first two dimensions so i have an array of RGB values. this one's got me
> completely stumped. i'm hoping there's just some function i'm not seeing
> in the docs, but i'd be just as happy with a bit of Numeric magic.

It's not clear to me what you mean here.  If you have an array with
shape (n,m,3) and want to get (n*m,3), just use reshape(a,(n*m,3)).
Maybe you mean something more complicated than that?

Richard L. White    rlw at stsci.edu    http://sundog.stsci.edu/rick/
Space Telescope Science Institute
Baltimore, MD

More information about the NumPy-Discussion mailing list