adelaide

原帖:https://blog.csdn.net/wld914674505/article/details/80460042

 

numpy.reshape(a, newshape, order=\'C\')[source],参数`newshape`是啥意思?

官方文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

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)

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

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

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

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

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

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

分类:

技术点:

相关文章: