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

  • answered 2020-01-14 01:35 Christian

    Make sure to write back to A if you use np.append, as in A = np.append(A,X) -- the top-level numpy functions like np.insert and np.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 the np.ndarray if you use append, so honestly, I think you just want a regular list 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.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],

  • answered 2020-01-14 02:20 hpaulj

    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)