Python中reshape函数参数-1的意思?

1、要记住,python默认是按行取元素

-1是模糊控制的意思 比如人reshape(-1,2)固定2列 多少行不知道

结果:

2、出错情况

>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]])
因为 a 总共有 6 个元素,reshape 成一个二维数组,指定第一维的长度是3(即 3 行),numpy 可以自动推断出第二维的长度是 2 (6 除以 3 等于 2)。
我们可以再试一下如果有多个维度没有指定长度的话会怎样。
>>> np.reshape(a, (-1,-1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshape
    return reshape(newshape, order=order)
ValueError: can only specify one unknown dimension
>>> np.reshape(a, (-1,-1)) Traceback (most recent call last): File " ", line 1, in File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshape return reshape(newshape, order=order) ValueError: can only specify one unknown dimension
如果出现了无法整除的情况呢?
np.reshape(a, (4,-1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshapereturn reshape(newshape, order=order)
ValueError: total size of new array must be
np.reshape(a, (4,-1)) Traceback (most recent call last): File " ", line 1, in File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshapereturn reshape(newshape, order=order) ValueError: total size of new array must be
>>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]]) 因为 a 总共有 6 个元素,reshape 成一个二维数组,指定第一维的长度是3(即 3 行),numpy 可以自动推断出第二维的长度是 2 (6 除以 3 等于 2)。 我们可以再试一下如果有多个维度没有指定长度的话会怎样。 >>> np.reshape(a, (-1,-1)) Traceback (most recent call last): File " ", line 1, in File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshape return reshape(newshape, order=order) ValueError: can only specify one unknown dimension 如果出现了无法整除的情况呢? np.reshape(a, (4,-1)) Traceback (most recent call last): File " ", line 1, in File "/usr/local/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 224, in reshapereturn reshape(newshape, order=order) ValueError: total size of new array must be
经验分享 程序员 微信小程序 职场和发展