简体   繁体   English

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

[英]How does numpy.reshape() with order = 'F' work?

I thought I understood the reshape function in Numpy until I was messing around with it and came across this example: 我以为我理解了Numpy中的重塑功能,直到我搞砸了它并遇到了这个例子:

a = np.arange(16).reshape((4,4))

which returns: 返回:

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

This makes sense to me, but then when I do: 这对我来说很有意义,但是当我这样做时:

a.reshape((2,8), order = 'F')

it returns: 它返回:

array([[0,  8,  1,  9,  2, 10, 3, 11],
       [4, 12,  5, 13,  6, 14, 7, 15]])

I would expect it to return: 我希望它能回归:

array([[0, 4,  8, 12, 1, 5,  9, 13],
       [2, 6, 10, 14, 3, 7, 11, 15]])

Can someone please explain what is happening here? 有人可以解释一下这里发生了什么吗?

The elements of a in order 'F' 的元件a为了“F”

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

are [0,4,8,12,1,5,9 ...] 是[0,4,8,12,1,5,9 ...]

Now rearrange them in a (2,8) array. 现在用(2,8)数组重新排列它们。

I think the reshape docs talks about raveling the elements, and then reshaping them. 我认为reshape文档谈论了对元素的粗暴,然后重新塑造它们。 Evidently the ravel is done first. 显然,首先完成了ravel。

Experiment with a.ravel(order='F').reshape(2,8) . 尝试a.ravel(order='F').reshape(2,8)

Oops, I get what you expected: 哎呀,我得到了你的期望:

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

OK, I have to keep the 'F' order during the 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

From np.reshape docs 来自np.reshape docs

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. 您可以将重塑视为首先对数组进行整形(使用给定的索引顺序),然​​后使用与raveling相同的索引顺序将raveled数组中的元素插入到新数组中。

The notes on order are fairly long, so it's not surprising that the topic is confusing. order上的注释相当长,所以这个主题令人困惑也就不足为奇了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM