问题描述
我正在尝试将数组从形状(a,b,c)
整形为(b,c,a)
,以便如果我的表是B而我的表新表为B1,然后 B [n,::] = B1 [:,:,n]
表示介于0和a之间的某个n.例如,我尝试了类似的方法,
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))
但是
B [1,:,:] = array([[2],[4],[21]])
和
B1 [:,:,1] = array([[2],[21],[1]])
这不是我想要的,我期望他们是平等的.任何建议将不胜感激.
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.
推荐答案
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
保持顺序,只是重新排列尺寸的大小:
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]]])
请注意,您可以按照创建 B
时所使用的顺序读取 1,2,23,2,...
.
notice that you can read the 1,2,23,2,...
in the same order that you used when creating B
.
转置
是不同的操作:
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])
1,2,23,...
顺序仍然存在-如果您读取这些行.但是混乱的秩序已经改变.
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]])
这篇关于如何在保留顺序的同时重塑数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!