numpy.reshape()函数

numpy.reshape(a, newshape, order=‘C’)[source],参数newshape是啥意思?
根据 Numpy 文档 (https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy-reshape) 的解释:

newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

大意是说,数组新的 shape 属性应该要与原来的配套,如果等于 -1 的话,那么 Numpy 会根据剩下的维度计算出数组的另外一个 shape 属性值。

举几个例子或许就清楚了,有一个数组 z,它的 shape 属性是 (4, 4)

z = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])
z.shape
(4, 4)
z.reshape(-1)

也就是说,先前我们不知道 z 的 shape 属性是多少,但是想让 z 变成只有一列,行数不知道多少,通过z.reshape(-1,1),Numpy 自动计算出有 12 行,新的数组 shape 属性为 (16, 1),与原来的(4, 4) 配套。

z.reshape(-1,1)
 array([[ 1],
        [ 2],
        [ 3],
        [ 4],
        [ 5],
        [ 6],
        [ 7],
        [ 8],
        [ 9],
        [10],
        [11],
        [12],
        [13],
        [14],
        [15],
        [16]])
z.reshape(-1, 2)

newshape 等于 -1,列数等于 2,行数未知,reshape 后的 shape 等于 (8, 2)

 z.reshape(-1, 2)
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10],
       [11, 12],
       [13, 14],
       [15, 16]])

同理,只给定行数,newshape 等于 -1,Numpy 也可以自动计算出新数组的列数。