How to change array shapes in in numpy?

后端 未结 4 1991
你的背包
你的背包 2020-12-11 16:29

If I create an array X = np.random.rand(D, 1) it has shape (3,1):

[[ 0.31215124]
 [ 0.84270715]
 [ 0.41846041]]

I

相关标签:
4条回答
  • 2020-12-11 16:53

    You can set the shape directy i.e.

    A.shape = (3L, 1L)
    

    or you can use the resize function:

    A.resize((3L, 1L))
    

    or during creation with reshape

    A = np.array([0,1,2]).reshape((3L, 1L))
    
    0 讨论(0)
  • 2020-12-11 16:56

    The numpy module has a reshape function and the ndarray has a reshape method, either of these should work to create an array with the shape you want:

    import numpy as np
    A = np.reshape([1, 2, 3, 4], (4, 1))
    # Now change the shape to (2, 2)
    A = A.reshape(2, 2)
    

    Numpy will check that the size of the array does not change, ie prod(old_shape) == prod(new_shape). Because of this relation, you're allowed to replace one of the values in shape with -1 and numpy will figure it out for you:

    A = A.reshape([1, 2, 3, 4], (-1, 1))
    
    0 讨论(0)
  • 2020-12-11 16:59

    You ou can assign a shape tuple directly to numpy.ndarray.shape.

    A.shape = (3,1)
    
    0 讨论(0)
  • 2020-12-11 17:08
    A=np.array([0,1,2])
    A.shape=(3,1)
    

    or

    A=np.array([0,1,2]).reshape((3,1))  #reshape takes the tuple shape as input
    
    0 讨论(0)
提交回复
热议问题