python - How to reshape my 4D-np.array to a 2D matrix and keep the structure?
问题描述
Let's say I have an 4D np.array that consists of 4 groups of 4x4 matrices:
array([[[[1., 1.],
[1., 1.]],
[[2., 2.],
[2., 2.]],
[[3., 3.],
[3., 3.]],
[[4., 4.],
[4., 4.]]],
[[[5., 5.],
[5., 5.]],
[[6., 6.],
[6., 6.]],
[[7., 7.],
[7., 7.]],
[[8., 8.],
[8., 8.]]],
[[[9., 9.],
[9., 9.]],
[[10., 10.],
[10., 10.]],
[[11., 11.],
[11., 11.]],
[[12., 12.],
[12., 12.]]],
[[[13., 13.],
[13., 13.]],
[[14., 14.],
[14., 14.]],
[[15., 15.],
[15., 15.]],
[[16., 16.],
[16., 16.]]]])
Now I want to reshape it to a single matrix so that I can have the groups in rows (but only the values, not as a matrix). I want to plot the 4x4 matrices next to each other in a single plot with matplotlib's imshow
function, so it should look like this:
[[ 1., 1., 2., 2., 3., 3., 4., 4.],
[ 1., 1., 2., 2., 3., 3., 4., 4.],
[ 5., 5., 6., 6., 7., 7., 8., 8.],
[ 5., 5., 6., 6., 7., 7., 8., 8.],
[ 9., 9., 10., 10., 11., 11., 12., 12.],
[ 9., 9., 10., 10., 11., 11., 12., 12.],
[13., 13., 14., 14., 15., 15., 16., 16.],
[13., 13., 14., 14., 15., 15., 16., 16.]]
Is this even possible? I would like to use only numpy functions and avoid for-loops for performance reasons, but if that's not possible another solution would also be great.
解决方案
这是我要做的:
# other sample:
arr=np.arange(64).reshape(4,4,2,2)
arr.swapaxes(2,1).reshape(arr.shape[0] * arr.shape[2],-1)
输出:
array([[ 0, 1, 4, 5, 8, 9, 12, 13],
[ 2, 3, 6, 7, 10, 11, 14, 15],
[16, 17, 20, 21, 24, 25, 28, 29],
[18, 19, 22, 23, 26, 27, 30, 31],
[32, 33, 36, 37, 40, 41, 44, 45],
[34, 35, 38, 39, 42, 43, 46, 47],
[48, 49, 52, 53, 56, 57, 60, 61],
[50, 51, 54, 55, 58, 59, 62, 63]])
推荐阅读
- c# - 删除每行字符串上的字符(C#)
- python - 无法绘制我想要的
- python - 在 django 中使用 slugify 后的详细页面错误
- c# - 如何更改我的代码,以便使用 Entity Framework 将实体动态添加到我的数据库中?
- c# - xsd 文件内容 xml 未在 chrome 浏览器中加载
- amcharts - AMCharts - 屏幕阅读器不显示折线图的任何内容
- python - 使用用户定义的刻度从 tsv 文件中的数据绘制 2D 散点图
- javascript - Javascript将字符串分解为变量并添加空格
- java - 将泛型通配符类型传递给接受泛型类型的方法
- php - 在多个终端上运行 Behat Selenium 场景有什么问题吗?