Python 将 3d 数组重塑为 2d
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33211988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Reshape 3d array into 2d
提问by pallago
I want to reshape the numpy array as it is depicted, from 3D to 2D. Unfortunately, the order is not correct.
我想重塑 numpy 数组,从 3D 到 2D。不幸的是,顺序不正确。
A assume to have a numpy array (1024, 64, 100) and want to convert it to (1024*100, 64).
假设有一个 numpy 数组 (1024, 64, 100) 并希望将其转换为 (1024*100, 64)。
Does anybody has an idea how to maintain the order?
有人知道如何维护订单吗?
I have a sample data
我有一个样本数据
data[0,0,0]=1
data[0,1,0]=2
data[0,2,0]=3
data[0,3,0]=4
data[1,0,0]=5
data[1,1,0]=6
data[1,2,0]=7
data[1,3,0]=8
data[2,0,0]=9
data[2,1,0]=10
data[2,2,0]=11
data[2,3,0]=12
data[0,0,1]=20
data[0,1,1]=21
data[0,2,1]=22
data[0,3,1]=23
data[1,0,1]=24
data[1,1,1]=25
data[1,2,1]=26
data[1,3,1]=27
data[2,0,1]=28
data[2,1,1]=29
data[2,2,1]=30
data[2,3,1]=31
and I would like to have an outcome like this:
我希望有这样的结果:
array([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[ 20., 21., 22., 23.],
[ 24., 25., 26., 27.],
[ 28., 29., 30., 31.]])
Moreover, I would also like to have the reshaping in the other way, i.e. from:
此外,我还想以另一种方式进行重塑,即来自:
array([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[ 20., 21., 22., 23.],
[ 24., 25., 26., 27.],
[ 28., 29., 30., 31.]])
to the desired output:
到所需的输出:
[[[ 1. 20.]
[ 2. 21.]
[ 3. 22.]
[ 4. 23.]]
[[ 5. 24.]
[ 6. 25.]
[ 7. 26.]
[ 8. 27.]]
[[ 9. 28.]
[ 10. 29.]
[ 11. 30.]
[ 12. 31.]]]
采纳答案by Divakar
It looks like you can use numpy.transpose
and then reshape, like so -
看起来你可以使用numpy.transpose
然后重塑,就像这样 -
data.transpose(2,0,1).reshape(-1,data.shape[1])
Sample run -
样品运行 -
In [63]: data
Out[63]:
array([[[ 1., 20.],
[ 2., 21.],
[ 3., 22.],
[ 4., 23.]],
[[ 5., 24.],
[ 6., 25.],
[ 7., 26.],
[ 8., 27.]],
[[ 9., 28.],
[ 10., 29.],
[ 11., 30.],
[ 12., 31.]]])
In [64]: data.shape
Out[64]: (3, 4, 2)
In [65]: data.transpose(2,0,1).reshape(-1,data.shape[1])
Out[65]:
array([[ 1., 2., 3., 4.],
[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.],
[ 20., 21., 22., 23.],
[ 24., 25., 26., 27.],
[ 28., 29., 30., 31.]])
In [66]: data.transpose(2,0,1).reshape(-1,data.shape[1]).shape
Out[66]: (6, 4)
To get back original 3D array, use reshape
and then numpy.transpose
, like so -
要取回原始 3D 数组,请使用reshape
然后numpy.transpose
,像这样 -
In [70]: data2D.reshape(np.roll(data.shape,1)).transpose(1,2,0)
Out[70]:
array([[[ 1., 20.],
[ 2., 21.],
[ 3., 22.],
[ 4., 23.]],
[[ 5., 24.],
[ 6., 25.],
[ 7., 26.],
[ 8., 27.]],
[[ 9., 28.],
[ 10., 29.],
[ 11., 30.],
[ 12., 31.]]])