尝试变化:
In [1]: np.arange(12).reshape(3,4)
Out[1]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [2]: np.arange(12).reshape([3,4])
Out[2]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [3]: np.arange(12).reshape((3,4))
Out[3]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
使用reshape 方法,形状可以是参数、元组或列表。在reshape 函数中必须在列表或元组中,以将它们与第一个数组参数分开
In [4]: np.reshape(np.arange(12), (3,4))
Out[4]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
是的,可以使用一个-1。重塑的总大小是固定的,因此可以从其他值中推导出一个值。
In [5]: np.arange(12).reshape(-1,4)
Out[5]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
方法文档有这样的注释:
与免费功能numpy.reshape 不同,ndarray 上的此方法允许
要作为单独参数传入的 shape 参数的元素。
例如,a.reshape(10, 11) 等价于
a.reshape((10, 11)).
这是一个内置函数,但签名看起来像x.reshape(*shape),只要值有意义,它就会尝试灵活。