5

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 Answers 3

4

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, :]
Sign up to request clarification or add additional context in comments.

2 Comments

Panzer, ich begruesse sie :D Thanks a lot that worked great! I resorted back to using for loops which obviously isn't great. do you know how well your solution works when initializing larger arrays?
@tinkerbell ;-) Is that Germish for I salute you? Doesn't really work in German I'm afraid. --- This should be reasonably fast, but if you want the absolutely fastest, then you should probably have a look at this.
1

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)

1 Comment

I think this is the nicest solution, but how would I extend this to the N dimension?
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.