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.

chesschi
  • 666
  • 1
  • 8
  • 36
  • 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. – hpaulj Dec 12 '17 at 06:19

1 Answers1

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)
tom10
  • 67,082
  • 10
  • 127
  • 137