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.
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?
Make sure to write back to
Aif you use
np.append, as in
A = np.append(A,X)-- the top-level numpy functions like
np.appendare usually immutable, so even though it gives you a value back, it's your job to store it.
np.arraylikes to flatten the
np.ndarrayif you use append, so honestly, I think you just want a regular
listfor 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.43351171e-316, 4.32573840e-317, 4.58492919e-320, ..., 1.14551501e-259, 6.01347002e-154, 1.39804329e-076], [1.39803697e-076, 1.39804328e-076, 1.39642638e-076, ..., 1.18295070e-076, 7.06474122e-096, 6.01347002e-154], [1.39804328e-076, 1.39642638e-076, 1.39804065e-076, ..., 1.05118732e-153, 6.01334510e-154, 3.24245662e-086], ...
In : A = np.array() In : A.shape Out: (0,) In : 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 : np.concatenate([A, np.arange(3)]) Out: 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 : X = np.ones((1000,32,32)) In : np.concatenate([X,X,X], axis=1).shape Out: (1000, 96, 32)