0

I want create 3d array with unknown length and append to the array as follows:

a = np.array([])
for n in range(1,3):
    data=np.full((2,3),n)
    a = np.append(a,data,axis=0)
print(a) 

The expected output is:

[[[1,1,1]
  [1,1,1]]

 [[2,2,2]
  [2,2,2]]]

However, I got an error:

ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)

How to declare an empty 3d numpy array with unknown length and append to it?

5
  • There isn't such a thing as an array of unknown length. And no clear equivalent of list [], or list append. Commented Dec 1, 2020 at 15:17
  • @hpaulj : I have multiple nested loops with several if conditions. When an if condition is true, which is not known in advance, then I want to append the my 2d data to the 3d array. That is why the length in the 3rd dimension is unknown. Commented Dec 1, 2020 at 16:08
  • The shape of the final result might not be known before hand, but that's not the same as saying the shape of an existing array is unknown. np.array([]).shape gives a result. So does np.array([[]]).shape or np.zeros((0,2,3)).shape. Commented Dec 1, 2020 at 16:11
  • Yes. I mean that the shape of the final result is unknown beforehand. Commented Dec 1, 2020 at 16:13
  • np.append is a cover function for np.concatenate. Especially when axis is provided all it does is np.concatenate((a,b), axis=0). That means you have to understand dimensions, and understand what concatenate expects. There's no room for sloppiness here. Commented Dec 1, 2020 at 16:13

1 Answer 1

1

It's better performance-wise (and easier) to create a list of your 2d arrays, then to call numpy.stack():

a = []
for n in range(1, 3):
    data = np.full((2, 3), n)
    a.append(data)
a = np.stack(a)
print(a)
print(a.shape) # <- (2, 2, 3)

You can also append to the list (a) 2d arrays in a list-of-lists structure (meaning, they don't have to be numpy arrays) and call np.stack() on that "list of lists of lists", would work too.

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.