Python中reshape函数参数-1的意思

根据numpy的reshape文档
One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
举个例子

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

Numpy自动计算出有16行,新的数组shape属性为(16, 1),与原来的(4, 4)配套。

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

同理。

转载自 Python中reshape函数参数-1的意思

猜你喜欢

转载自blog.csdn.net/cainiaohudi/article/details/79980826