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

标签 python numpy reshape

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

相关文章:

在 R 中重新格式化数据框

python - Keras:致密层和激活层之间的形状不匹配

python - 将行转换为 Pandas 数据框中的列

numpy:在二维数组的每一行中找到值的第一个索引

python - 如何在散点图中解释相同的数据点?

python - 如何更改满足特定条件的数据框中的第一个值

python - Pandas 在不同数量的行中为每个 ID 选择三行

r - 将数据从多行转换为多列

python - 获取scipy的gmres迭代方法的迭代次数

python - 在 Django/mod_wsgi 中进行一次性初始化的安全方法是什么?