How to append to a ndarray
I'm new to Numpy library from Python and I'm not sure what I'm doing wrong here, could you help me please with this?
So, I initialize my ndarray like this.
A = np.array([])
And then I'm training to append into this array A a new array X which has a shape like (1000,32,32) if has any importance.
np.insert(A, X)
The problem here is that if I'm checking the ndarray A after that it's empty, even though the ndarray X has elements inside. Could you explain me what exactly I'm doing wrong please?
2 answers

Make sure to write back to
A
if you usenp.append
, as inA = np.append(A,X)
 the toplevel numpy functions likenp.insert
andnp.append
are usually immutable, so even though it gives you a value back, it's your job to store it.np.array
likes to flatten thenp.ndarray
if you use append, so honestly, I think you just want a regularlist
for A, and that append method is mutable, so no need to write it back.>>> A = [] >>> X = np.ndarray((1000,32,32)) >>> A.append(X) >>> print(A) [array([[[1.43351171e316, 4.32573840e317, 4.58492919e320, ..., 1.14551501e259, 6.01347002e154, 1.39804329e076], [1.39803697e076, 1.39804328e076, 1.39642638e076, ..., 1.18295070e076, 7.06474122e096, 6.01347002e154], [1.39804328e076, 1.39642638e076, 1.39804065e076, ..., 1.05118732e153, 6.01334510e154, 3.24245662e086], ...

In [10]: A = np.array([]) In [11]: A.shape Out[11]: (0,) In [13]: np.concatenate([A, np.ones((2,3))])  ... 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)
So one first things you need to learn about numpy arrays is that they have
shape
, and a number of dimensions. Hopefully that error message is clear.Concatenate with another 1d array does work:
In [14]: np.concatenate([A, np.arange(3)]) Out[14]: array([0., 1., 2.])
But that is just
np.arange(3)
. The concatenate does nothing for us. OK, you might imagine starting a loop like this. But don't. This is not efficient.You could easily concatenate a list of arrays, as long as the dimensions obey the rules specified in the docs. Those rules are logical, as long as you take the dimensions of the arrays seriously.
In [15]: X = np.ones((1000,32,32)) In [16]: np.concatenate([X,X,X], axis=1).shape Out[16]: (1000, 96, 32)