How to reshape an array while preserving order?

时间秒杀一切 提交于 2021-01-28 20:11:52

问题


I am trying to reshape an array from shape (a,b,c) to (b,c,a) such that if my table is B and my new table is B1 then B[n,:,:]=B1[:,:,n] for some n between 0 and a. For example I tried something like,

B=np.array([[[1],[2],[23]],[[2],[4],[21]],[[6],[45],[61]],[[1],[34],[231]]])
B1=np.reshape(B,(3,1,4))

But

B[1,:,:]=array([[ 2],[ 4],[21]]) and

B1[:,:,1]=array([[ 2],[21],[ 1]]) which is not what I want I would've expected them to be equal. Any suggestions would be greatly appreciated.


回答1:


In [207]: B=np.array([[[1],[2],[23]],[[2],[4],[21]],[[6],[45],[61]],[[1],[34],[231]]])         
In [208]: B                                                                                    
Out[208]: 
array([[[  1],
        [  2],
        [ 23]],

       [[  2],
        [  4],
        [ 21]],

       [[  6],
        [ 45],
        [ 61]],

       [[  1],
        [ 34],
        [231]]])
In [209]: B.shape                                                                              
Out[209]: (4, 3, 1)

reshape keeps the order, just rearranging the size of the dimensions:

In [210]: B.reshape(3,1,4)                                                                     
Out[210]: 
array([[[  1,   2,  23,   2]],

       [[  4,  21,   6,  45]],

       [[ 61,   1,  34, 231]]])

notice that you can read the 1,2,23,2,... in the same order that you used when creating B.

transpose is a different operation:

In [211]: B.transpose(1,2,0)                                                                   
Out[211]: 
array([[[  1,   2,   6,   1]],

       [[  2,   4,  45,  34]],

       [[ 23,  21,  61, 231]]])
In [212]: _.shape                                                                              
Out[212]: (3, 1, 4)
In [213]: __.ravel()                                                                           
Out[213]: array([  1,   2,   6,   1,   2,   4,  45,  34,  23,  21,  61, 231])

The 1,2,23,... order is still there - if you read down the rows. But the raveled order has changed.

In [216]: B.transpose(1,2,0).ravel(order='F')                                                  
Out[216]: array([  1,   2,  23,   2,   4,  21,   6,  45,  61,   1,  34, 231])

In [217]: B[1,:,:]                                                                             
Out[217]: 
array([[ 2],
       [ 4],
       [21]])
In [218]: B.transpose(1,2,0)[:,:,1]                                                            
Out[218]: 
array([[ 2],
       [ 4],
       [21]])


来源:https://stackoverflow.com/questions/60402727/how-to-reshape-an-array-while-preserving-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!