作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
有没有办法将 2D 数组划分并 reshape 为 3D 数组。像下面的例子:
基本上,我的左边有一个 4x4 矩阵,我想要一个如图所示的 2x2x4 矩阵,这样我就可以在第 3 个轴上应用 numpy.mean。实际上,我拥有的矩阵非常庞大,所以这就是为什么循环遍历 block 不是一种选择。
非常感谢任何帮助。
最佳答案
对于您的示例,您可以使用 numpy.lib.stride_tricks.as_strided .
In [1]: A = np.arange(16).reshape(4, 4)
In [2]: A
Out[2]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
In [3]: strides = A.itemsize * np.array([8, 2, 4, 1])
In [4]: x = p.lib.stride_tricks.as_strided(A, shape = (2, 2, 2, 2), strides = strides)
In [4]: x
Out[4]:
array([[[[ 0, 1],
[ 4, 5]],
[[ 2, 3],
[ 6, 7]]],
[[[ 4, 5],
[ 8, 9]],
[[ 6, 7],
[10, 11]]]])
In [5]: x.reshape(4, 2, 2)
Out[5]:
array([[[ 0, 1],
[ 4, 5]],
[[ 2, 3],
[ 6, 7]],
[[ 8, 9],
[12, 13]],
[[10, 11],
[14, 15]]])
步长定义了遍历数组时要使用的偏移量(以字节为单位),as_strided
函数使您能够构建具有用户定义步长的新数组。
但是,我不知道它的效率如何以及它的扩展性如何适合您的使用。
关于python - Numpy - 将 2D 数组 reshape 并分区为 3D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31686989/
由于 App Store 拒绝二进制文件,我正在更新我的应用程序,因为我的应用程序在“信用”页面中包含指向网站的链接。我需要实现一个家长门来限制对“信用” View Controller 的访问。 我
我是一名优秀的程序员,十分优秀!