NumPy stack or append array to array

后端 未结 3 831
悲哀的现实
悲哀的现实 2021-01-27 13:50

I am starting with NumPy.

Given two np.arrays, queu and new_path:

queu = [ [[0 0]
          [0 1]]
       ]

new_p         


        
3条回答
  •  后悔当初
    2021-01-27 14:26

    In [741]: queu = np.array([[[0,0],[0,1]]])
    In [742]: new_path = np.array([[[0,0],[1,0],[2,0]]])
    In [743]: queu
    Out[743]: 
    array([[[0, 0],
            [0, 1]]])
    In [744]: queu.shape
    Out[744]: (1, 2, 2)
    In [745]: new_path
    Out[745]: 
    array([[[0, 0],
            [1, 0],
            [2, 0]]])
    In [746]: new_path.shape
    Out[746]: (1, 3, 2)
    

    You have defined 2 arrays, with shape (1,2,2) and (1,3,2). If you are puzzled about those shapes you need to reread some of the basic numpy introduction.

    hstack, vstack and append all call concatenate. With 3d arrays using them will just confuse matters.

    Joining on the 2nd axis, which is size 2 for one and 3 for the other, works, producing a (1,5,2) array. (This is equivalent to hstack)

    In [747]: np.concatenate((queu, new_path),axis=1)
    Out[747]: 
    array([[[0, 0],
            [0, 1],
            [0, 0],
            [1, 0],
            [2, 0]]])
    

    Trying to join on axis 0 (vstack) produces your error:

    In [748]: np.concatenate((queu, new_path),axis=0)
    ....
    ValueError: all the input array dimensions except for the concatenation axis must match exactly
    

    The concatenation axis is 0, but dimensions of axis 1 differ. Hence the error.

    Your target is not a valid numpy array. You could collect them together in a list:

    In [759]: alist=[queu[0], new_path[0]]
    In [760]: alist
    Out[760]: 
    [array([[0, 0],
            [0, 1]]), 
     array([[0, 0],
            [1, 0],
            [2, 0]])]
    

    Or an object dtype array - but that's more advanced numpy.

提交回复
热议问题