ValueError: all the input arrays must have same number of dimensions

后端 未结 4 941
既然无缘
既然无缘 2020-12-24 03:28

I\'m having a problem with np.append.

I\'m trying to duplicate the last column of 20x361 matrix n_list_converted by using the code below:

4条回答
  •  执念已碎
    2020-12-24 04:08

    The reason why you get your error is because a "1 by n" matrix is different from an array of length n.

    I recommend using hstack() and vstack() instead. Like this:

    import numpy as np
    a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
    b = a[:,-1:]                    # last column of that matrix.
    
    result = np.hstack((a,b))       # stack them horizontally like this:
    #array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
    #       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
    #       [16, 17, 18, 19, 20, 21, 22, 23, 23],
    #       [24, 25, 26, 27, 28, 29, 30, 31, 31]])
    

    Notice the repeated "7, 15, 23, 31" column. Also, notice that I used a[:,-1:] instead of a[:,-1]. My version generates a column:

    array([[7],
           [15],
           [23],
           [31]])
    

    Instead of a row array([7,15,23,31])


    Edit: append() is much slower. Read this answer.

提交回复
热议问题