Python将3d数组重塑为2d [英] Python Reshape 3d array into 2d
本文介绍了Python将3d数组重塑为2d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想重塑numpy数组,如图所示,从3D到2D.不幸的是,顺序不正确.
I want to reshape the numpy array as it is depicted, from 3D to 2D. Unfortunately, the order is not correct.
假设有一个numpy数组(1024、64、100),并且想要将其转换为(1024 * 100、64).
A assume to have a numpy array (1024, 64, 100) and want to convert it to (1024*100, 64).
有人知道如何维持订单吗?
Does anybody has an idea how to maintain the order?
我有一个样本数据
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
我想得到这样的结果:
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.]])
到所需的输出:
[[[ 1. 20.]
[ 2. 21.]
[ 3. 22.]
[ 4. 23.]]
[[ 5. 24.]
[ 6. 25.]
[ 7. 26.]
[ 8. 27.]]
[[ 9. 28.]
[ 10. 29.]
[ 11. 30.]
[ 12. 31.]]]
推荐答案
It looks like you can use numpy.transpose
and then reshape, like so -
data.transpose(2,0,1).reshape(-1,data.shape[1])
样品运行-
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)
要恢复原始3D阵列,请依次使用reshape
和numpy.transpose
-
To get back original 3D array, use reshape
and then numpy.transpose
, like so -
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.]]])
这篇关于Python将3d数组重塑为2d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文