numpy - 重塑 numpy 数组,进行转换并进行反向重塑
问题描述
这是我的问题:
我正在尝试对 numpy 数组进行整形后对其进行操作。
但是在这个操作之后,我想再次重塑我的数组以获得具有相同索引的原始形状。
所以我想找到合适的“反向重塑”,以便 inverse_reshape(reshape(a))==a
length = 10
a = np.arange(length^2).reshape((length,length))
#a.spape = (10,10)
b = (a.reshape((length//2, 2, -1, 2))
.swapaxes(1, 2)
.reshape(-1, 2, 2))
#b.shape = (25,2,2)
b = my_function(b)
#b.shape = (25,2,2) still the same shape
# b --> a ?
我知道 numpy reshape 函数不会复制数组,但 swapaxes 可以。
我怎样才能得到适当的重塑?
解决方案
只需颠倒a=>b
转换的顺序。
原作:
In [53]: a.reshape((length//2, 2, -1, 2)).shape
Out[53]: (5, 2, 5, 2)
In [54]: a.reshape((length//2, 2, -1, 2)).swapaxes(1,2).shape
Out[54]: (5, 5, 2, 2)
In [55]: b.shape
Out[55]: (25, 2, 2)
所以我们需要b
回到 4d 形状,将轴交换回来,然后重塑为原始a
形状:
In [56]: b.reshape(5,5,2,2).swapaxes(1,2).reshape(10,10)
Out[56]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
推荐阅读
- r - 连接字符串列并按字母顺序排列
- mongodb - 我怎样才能改变这个查询返回数据库中所有的平均值。mongodb
- javascript - 从数据库获取方法导致套接字挂起错误
- python - 求解具有一个变量的方程
- cordova-plugins - 连接到 Google Fit 同意屏幕拒绝多个权限之一将无法连接 - cordova 离子应用程序
- flutter - 如何观察数据变化
- html - 如何使用 css 动画一张一张地加载图像?
- c++ - 有没有办法在 2 个应用程序之间传递窗口句柄 HWND?
- c++ - 为什么 const 指针意外转换为 bool?
- javascript - 动态构建表时事件在 JQuery 中不起作用