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的意思

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页