python numpy 二维数组reshape成三维数组

  • Post author:
  • Post category:python


如下:

>>> a = np.arange(20)
>>> a.reshape((4,5))
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> a= a.reshape((4,5))
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> a=a.reshape((2,2,1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot reshape array of size 20 into shape (2,2,1)
>>> a=a.reshape((2,2,5))
>>> a
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9]],

       [[10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]]])
>>>

可以发现shape为4行,5列的数组变为shape为2,2,5的数组,每一行的数据没有改变,保持内部的结构



版权声明:本文为qq_44065334原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。