我以为我理解了 Numpy 中的 reshape 功能,直到我搞砸了它并遇到了这个例子:
a = np.arange(16).reshape((4,4))
返回:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
这对我来说很有意义,但是当我这样做时:
a.reshape((2,8), order = 'F')
它返回:
array([[0, 8, 1, 9, 2, 10, 3, 11],
[4, 12, 5, 13, 6, 14, 7, 15]])
我希望它会返回:
array([[0, 4, 8, 12, 1, 5, 9, 13],
[2, 6, 10, 14, 3, 7, 11, 15]])
有人可以解释一下这里发生了什么吗?
最佳答案
a
的元素按“F”顺序
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
是 [0,4,8,12,1,5,9 ...]
现在将它们重新排列在 (2,8) 数组中。
我认为
reshape
docs 谈到分解元素,然后 reshape 它们。显然,解谜是先完成的。试用
a.ravel(order='F').reshape(2,8)
.哎呀,我得到了你的期望:
In [208]: a = np.arange(16).reshape(4,4)
In [209]: a
Out[209]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
In [210]: a.ravel(order='F')
Out[210]: array([ 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15])
In [211]: _.reshape(2,8)
Out[211]:
array([[ 0, 4, 8, 12, 1, 5, 9, 13],
[ 2, 6, 10, 14, 3, 7, 11, 15]])
好的,我必须在 reshape 期间保持“F”顺序
In [214]: a.ravel(order='F').reshape(2,8, order='F')
Out[214]:
array([[ 0, 8, 1, 9, 2, 10, 3, 11],
[ 4, 12, 5, 13, 6, 14, 7, 15]])
In [215]: a.ravel(order='F').reshape(2,8).flags
Out[215]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
...
In [216]: a.ravel(order='F').reshape(2,8, order='F').flags
Out[216]:
C_CONTIGUOUS : False
F_CONTIGUOUS : True
来自
np.reshape
文档You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.
order
上的注释相当长,所以这个话题令人困惑也就不足为奇了。
关于python - order = 'F' 的 numpy.reshape() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973722/