Python: Add a column to numpy 2d array

后端 未结 5 1254
醉酒成梦
醉酒成梦 2021-01-02 04:44

I have a 60000 by 200 numpy array. I want to make it 60000 by 201 by adding a column of 1\'s to the right. (so every row is [prev, 1]) Concatenate with axis = 1 doesn\'t wor

5条回答
  •  生来不讨喜
    2021-01-02 05:29

    Under cover all the stack variants (including append and insert) end up doing a concatenate. They just precede it with some sort of array reshape.

    In [60]: A = np.arange(12).reshape(3,4)
    
    In [61]: np.concatenate([A, np.ones((A.shape[0],1),dtype=A.dtype)], axis=1)
    Out[61]: 
    array([[ 0,  1,  2,  3,  1],
           [ 4,  5,  6,  7,  1],
           [ 8,  9, 10, 11,  1]])
    

    Here I made a (3,1) array of 1s, to match the (3,4) array. If I wanted to add a new row, I'd make a (1,4) array.

    While the variations are handy, if you are learning, you should become familiar with concatenate and the various ways of constructing arrays that match in number of dimensions and necessary shapes.

提交回复
热议问题