order = 'F' 的 numpy.reshape() 如何工作?

问题描述 投票:0回答:2

我以为我理解了 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]])

有人可以解释一下这里发生了什么吗?

python numpy reshape
2个回答
14
投票

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
文档讨论了整理元素,然后重塑它们。显然是先完成了拆解。

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]])

好的,我必须在重塑过程中保持“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
文档

您可以将重塑视为首先对数组进行整理(使用给定的 索引顺序),然后将数组中的元素插入到 新数组使用与用于相同类型的索引排序 胡言乱语。

order
的注释相当长,因此主题令人困惑也就不足为奇了。


0
投票

正如文档提到的,“F”顺序改变第一个索引最快。这意味着重塑数组的第一个轴或 axis=0 将首先填充元素。

用言语来理解这个其实有点困难。所以我将在描述它们的同时附上一些女士绘画图像。

1. The source array is first flattened. In your case the array becomes like this

© www.soinside.com 2019 - 2024. All rights reserved.