python - 在 Python 中使用 reshape reshape 数组

标签 python numpy shapes reshape

我有一个如下所示的数组:

array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7, 7, 7]])

我怎样才能使用 reshape 将它分成 4 个夹头,这样它看起来像

array([[[0, 0, 0, 0],  
       [1, 1, 1, 1],  
       [2, 2, 2, 2],  
       [3, 3, 3, 3]],  
       [[0, 0, 0, 0],  
       [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]],
       [[4, 4, 4, 4],
       [5, 5, 5, 5],
       [6, 6, 6, 6],
       [7, 7, 7, 7]]])

我在 reshape(m,n,l) 中尝试了 m、n、l 的不同整数组合,但均无效。

最佳答案

编辑:抱歉,我没有意识到这是 3 维结果,而不是 4 维结果。要获得 3-d 的,您必须再次 reshape 形状。额外的 reshape 复制数据。

你不能,你也需要转置:

In [1]: a = np.arange(8)[:,None].repeat(8,axis=1)

In [2]: a
Out[2]: 
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7, 7, 7]])

In [3]: b = a.reshape(2,4,2,4)

In [4]: b
Out[4]: 
array([[[[0, 0, 0, 0],
         [0, 0, 0, 0]],
         ...
        [[7, 7, 7, 7],
         [7, 7, 7, 7]]]])

In [5]: b.transpose(0,2,1,3)
Out[5]: 
array([[[[0, 0, 0, 0],
         [1, 1, 1, 1],
         [2, 2, 2, 2],
         [3, 3, 3, 3]],

        [[0, 0, 0, 0],
         [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]],

        [[4, 4, 4, 4],
         [5, 5, 5, 5],
         [6, 6, 6, 6],
         [7, 7, 7, 7]]]])

关于python - 在 Python 中使用 reshape reshape 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482527/

相关文章:

Python - 初学者用 Beautiful Soup 4 抓取 - onmouseover

python - 蒙特卡洛模拟无法识别连通图

android - 从 Bitmap 中剪切多点 ploygon 并将其置于透明状态

c - 在C语言编程中用递归制作形状

matlab - 连接不连续的骨架形状和不连续的线条

python - 如何从 Windows 中的 c 程序执行 python (2.7) 脚本

python - 在没有 root 访问权限的情况下安装 Tkinter

python - 使用 BLAS 实现更快的 python 内积

python - Numpy:考虑项目的邻居及其在数组中的位置的快速计算

python - Numpy 数组与 C++ vector 在内存效率方面的对比