Py中reshape中的-1表示什么【转载】

转自:https://blog.csdn.net/weixin_39449570/article/details/78619196

1.新数组的shape属性应该要与原来数组的一致,即新数组元素数量与原数组元素数量要相等。一个参数为-1时,那么reshape函数会根据另一个参数的维度计算出数组的另外一个shape属性值。

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

>>> print(z)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]
>>> print(z.shape)
(4, 4)
>>> print(z.reshape(-1))
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
>>> print(z.reshape(-1,1))  #我们不知道z的shape属性是多少,
                            #但是想让z变成只有一列,行数不知道多少,
                            #通过`z.reshape(-1,1)`,Numpy自动计算出有16行,
                            #新的数组shape属性为(16, 1),与原来的(4, 4)配套。
[[ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10]
 [11]
 [12]
 [13]
 [14]
 [15]
 [16]]
>>> print(z.reshape(2,-1))
[[ 1  2  3  4  5  6  7  8]
 [ 9 10 11 12 13 14 15 16]]
原文地址:https://www.cnblogs.com/BlueBlueSea/p/10654918.html