Python中reshape函数参数-1的意思?
程序员文章站
2022-05-31 18:55:28
...
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]])
我们可以再试一下如果有多个维度没有指定长度的话会怎样。
>>> 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, (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 reshape
return reshape(newshape, order=order)
ValueError: total size of new array must be