Numpy Vector (N,1) dimension -> (N,) dimension conversion

后端 未结 5 2055
耶瑟儿~
耶瑟儿~ 2020-12-01 17:35

I have a question regarding the conversion between (N,) dimension arrays and (N,1) dimension arrays. For example, y is (2,) dimension.

A=np.array([[1,2],[3,4         


        
5条回答
  •  失恋的感觉
    2020-12-01 18:12

    Slice along the dimension you want, as in the example below. To go in the reverse direction, you can use None as the slice for any dimension that should be treated as a singleton dimension, but which is needed to make shapes work.

    In [786]: yy = np.asarray([[11],[7]])
    
    In [787]: yy
    Out[787]:
    array([[11],
           [7]])
    
    In [788]: yy.shape
    Out[788]: (2, 1)
    
    In [789]: yy[:,0]
    Out[789]: array([11, 7])
    
    In [790]: yy[:,0].shape
    Out[790]: (2,)
    
    In [791]: y1 = yy[:,0]
    
    In [792]: y1.shape
    Out[792]: (2,)
    
    In [793]: y1[:,None]
    Out[793]:
    array([[11],
           [7]])
    
    In [794]: y1[:,None].shape
    Out[794]: (2, 1)
    

    Alternatively, you can use reshape:

    In [795]: yy.reshape((2,))
    Out[795]: array([11,  7])
    

提交回复
热议问题