The meaning of reshape (-1)

The shape attribute of the new array should be consistent with the original array, that is, the number of elements in the new array should be equal to the number of elements in the original array. When one parameter is -1, then the reshape function will calculate another shape attribute value of the array according to the dimension of the other parameter. Here are a few examples to understand:

>>> 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]]

 

 

Published 943 original articles · Like 136 · Visit 330,000+

Guess you like

Origin blog.csdn.net/weixin_36670529/article/details/105038060