Numpy reshape 1d to 2d array with 1 column

后端 未结 7 604
一生所求
一生所求 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:15

    There are mainly two ways to go from 1 dimensional array (N) to 2 dimensional array with 1 column
    (N x 1):

    1. Indexing with np.newaxis;
    2. Reshape with reshape() method.
    x = np.array([1, 2, 3])  # shape: (3,) <- 1d
    
    x[:, None]               # shape: (3, 1) <- 2d (single column matrix)
    x[:, np.newaxis]         # shape: (3, 1) <- a meaningful alias to None
    
    x.reshape(-1, 1)         # shape: (3, 1)
    

提交回复
热议问题