3
votes

Hi numpy beginner here:

I'm trying to create an array of shape NxWxHx2 initialized with the corresponding index values. in this case W=H always.

e.g.: for an array of shape Nx5x5x2, if I would write it on Paper it should be:

N times the following


(0,0) (0,1) (0,2) (0,3) (0,4)

(1,0) (1,1) (1,2) (1,3) (1,4)

(2,0) (2,1) (2,2) (2,3) (2,4)

(3,0) (3,1) (3,2) (3,3) (3,4)

(4,0) (4,1) (4,2) (4,3) (4,4)


I looked into the "arange" fkt as well as extending arrays with "newaxis" but couldn't manage to get the desired result.

sorry for the terrible formating.

thanks for the help!

edit: I came up with something like this but it isn't nice. for an array of shape 1x3x3x2

t = np.empty([1,3,3,2])
for n in range(1):
    for i in range(3):
        for p in range(3):
            for r in range(2):
                if r == 0:
                    t[n,i,p,r]=i
                else:
                    t[n,i,p,r]=p    
3

3 Answers

1
votes

I'd start with

W=5; H=5; N=3

a = [[(h, w) for w in range(W)] for h in range(H)]
Out[1]: 
[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
 [(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)],
 [(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)],
 [(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)],
 [(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]

arr = [a for i in range(N)]

arr = np.array(arr)
2
votes

One way is to allocate an empty array

>> out = np.empty((N, 5, 5, 2), dtype=int)

and then use broadcasting, for example

>>> out[...] = np.argwhere(np.ones((5, 5), dtype=np.int8)).reshape(5, 5, 2)

or

>>> out[...] = np.moveaxis(np.indices((5, 5)), 0, 2)

or

>>> out[..., 0] = np.arange(5)[None, :, None]
>>> out[..., 1] = np.arange(5)[None, None, :]
0
votes
import numpy as np

x, y = np.mgrid[0:5, 0:5]

arr = np.array(zip(y.ravel(), x.ravel()), dtype=('i,i')).reshape(x.shape)

This should also work and is really just an alternative to Paul Panzer's reply.