Numpy reshape 1d to 2d array with 1 column

后端 未结 7 622
一生所求
一生所求 2020-12-08 15:08

In numpy the dimensions of the resulting array vary at run time. There is often confusion between a 1d array and a 2d array with 1 column. In one case I can ite

7条回答
  •  难免孤独
    2020-12-08 15:29

    You could do -

    ar.reshape(ar.shape[0],-1)
    

    That second input to reshape : -1 takes care of the number of elements for the second axis. Thus, for a 2D input case, it does no change. For a 1D input case, it creates a 2D array with all elements being "pushed" to the first axis because of ar.shape[0], which was the total number of elements.

    Sample runs

    1D Case :

    In [87]: ar
    Out[87]: array([ 0.80203158,  0.25762844,  0.67039516,  0.31021513,  0.80701097])
    
    In [88]: ar.reshape(ar.shape[0],-1)
    Out[88]: 
    array([[ 0.80203158],
           [ 0.25762844],
           [ 0.67039516],
           [ 0.31021513],
           [ 0.80701097]])
    

    2D Case :

    In [82]: ar
    Out[82]: 
    array([[ 0.37684126,  0.16973899,  0.82157815,  0.38958523],
           [ 0.39728524,  0.03952238,  0.04153052,  0.82009233],
           [ 0.38748174,  0.51377738,  0.40365096,  0.74823535]])
    
    In [83]: ar.reshape(ar.shape[0],-1)
    Out[83]: 
    array([[ 0.37684126,  0.16973899,  0.82157815,  0.38958523],
           [ 0.39728524,  0.03952238,  0.04153052,  0.82009233],
           [ 0.38748174,  0.51377738,  0.40365096,  0.74823535]])
    

提交回复
热议问题