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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ASE
  • 1,702
  • 2
  • 21
  • 29
  • There isn't such a thing as an array of unknown length. And no clear equivalent of list [], or list append. – hpaulj Dec 01 '20 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. – ASE Dec 01 '20 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`. – hpaulj Dec 01 '20 at 16:11
  • Yes. I mean that the shape of the final result is unknown beforehand. – ASE Dec 01 '20 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. – hpaulj Dec 01 '20 at 16:13

1 Answers1

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.

itaishz
  • 701
  • 1
  • 4
  • 10