Numpy reshape an array with specific order

前端 未结 4 1520
梦毁少年i
梦毁少年i 2021-01-24 01:25

Let\'s say I have this array x:

x = array([1, 2, 3, 4, 5, 6, 7, 8])
x.shape = (8,1)

I want to reshape it to become

array([[1, 3         


        
4条回答
  •  后悔当初
    2021-01-24 02:10

    The easiest way to do this is to specify the orderargument in reshape function.


    You need the Fortran order.

    Side note: Matlab by default is using Fortran order but in python you need to specify that.


    Use this:

    x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
    y = x.reshape(2,4, order='F')
    
    print(y)
    #array([[1, 3, 5, 7],
    #       [2, 4, 6, 8]])
    

提交回复
热议问题