numpy中的reshape中参数为-1

Posted liuys635

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了numpy中的reshape中参数为-1相关的知识,希望对你有一定的参考价值。

上篇文章中的reshape(-1,2),有的时候不明白为什么会有参数-1,可以通过查找文档中的reshape()去理解这个问题

根据Numpy文档(html#numpy-reshape)的解释:

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)

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

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

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

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

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

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

以上是关于numpy中的reshape中参数为-1的主要内容,如果未能解决你的问题,请参考以下文章

python基础之numpy.reshape详解

numpy.reshape使用条件

利用Python中的numpy.ndarray.reshape()对阵列形状进行调整

numpy reshape 中的 -1 是啥意思? [复制]

numpy.reshape()使用方法

numpy 中的reshape,flatten,ravel 数据平展,多维数组变成一维数组