2

This link suggests that we can use a Python list to add elements to it and convert it to numpy array using np.array with unknown length like this:

a = []
for x in y:
    a.append(x)
a = np.array(a)

Let's say x is a numpy.ndarray with shape (h,w) but h and w are unknown, how can we add elements to second axis of ndarray a in a loop to make a becomes (h,w,d) where d is the number of iterations?

I understand we can use dstack to add elements together to become (h,w,d) but I am not too sure how to do this in a loop.

1
  • 1
    Also play around with np.stack. WIth the default axis value it behaves much like np.array, but you can specify other axis values. Commented Dec 12, 2017 at 6:19

1 Answer 1

2

You can do a similar thing, but with x as 2D numpy arrays. That is, if you don't know the number of arrays ahead of time, you can collect them in a list and then convert them to a single 3D array in one step. The code would look very similar to your example:

gen2d = (i*np.ones((2,2)) for i in range(random.randint(1, 10))) # a generator of unknown N

a = []
for x in gen2d:
    a.append(x)
a = np.dstack(a)

a.shape  # (2, 2, 7)
Sign up to request clarification or add additional context in comments.

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.