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

后端 未结 5 2039
耶瑟儿~
耶瑟儿~ 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])
    
    0 讨论(0)
  • 2020-12-01 18:13

    What about vice versa? Numpy Numpy Vector (N,) dimension conversion ->Vector (N,1) dimension dimension conversion

    0 讨论(0)
  • 2020-12-01 18:18

    the opposite translation can be made by:

    np.atleast_2d(y).T
    
    0 讨论(0)
  • 2020-12-01 18:24

    reshape works for this

    a  = np.arange(3)        # a.shape  = (3,)
    b  = a.reshape((3,1))    # b.shape  = (3,1)
    b2 = a.reshape((-1,1))   # b2.shape = (3,1)
    c  = b.reshape((3,))     # c.shape  = (3,)
    c2 = b.reshape((-1,))    # c2.shape = (3,)
    

    note also that reshape doesn't copy the data unless it needs to for the new shape (which it doesn't need to do here):

    a.__array_interface__['data']   # (22356720, False)
    b.__array_interface__['data']   # (22356720, False)
    c.__array_interface__['data']   # (22356720, False)
    
    0 讨论(0)
  • 2020-12-01 18:29

    Use numpy.squeeze:

    >>> x = np.array([[[0], [1], [2]]])
    >>> x.shape
    (1, 3, 1)
    >>> np.squeeze(x).shape
    (3,)
    >>> np.squeeze(x, axis=(2,)).shape
    (1, 3)
    
    0 讨论(0)
提交回复
热议问题