How to make a 2d numpy array a 3d array?

后端 未结 8 1696
小鲜肉
小鲜肉 2020-12-08 02:24

I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this?

8条回答
  •  死守一世寂寞
    2020-12-08 03:23

    import numpy as np
    
    # create a 2D array
    a = np.array([[1,2,3], [4,5,6], [1,2,3], [4,5,6],[1,2,3], [4,5,6],[1,2,3], [4,5,6]])
    
    print(a.shape) 
    # shape of a = (8,3)
    
    b = np.reshape(a, (8, 3, -1)) 
    # changing the shape, -1 means any number which is suitable
    
    print(b.shape) 
    # size of b = (8,3,1)
    

提交回复
热议问题