numpy.reshape()与order ='F'如何工作? [英] How does numpy.reshape() with order = 'F' work?

查看:868
本文介绍了numpy.reshape()与order ='F'如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我了解Numpy中的重塑功能,直到我弄乱它并遇到以下示例:

I thought I understood the reshape function in Numpy until I was messing around with it and came across this example:

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

返回:

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

它返回:

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

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

Can someone please explain what is happening here?

推荐答案

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

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

现在将它们重新排列为(2,8)数组.

Now rearrange them in a (2,8) array.

我认为reshape文档讨论了如何拆散元素,然后重塑它们的形状.显然,先完成了.

I think the reshape docs talks about raveling the elements, and then reshaping them. Evidently the ravel is done first.

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

好的,在重塑过程中我必须保持'F'顺序

OK, I have to keep the 'F' order during the reshape

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文档

您可以将重塑视为首先散布数组(使用给定 索引顺序),然​​后将raveled数组中的元素插入到 新数组使用与 闲逛.

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上的注释相当长,因此该主题令人困惑也就不足为奇了.

The notes on order are fairly long, so it's not surprising that the topic is confusing.

这篇关于numpy.reshape()与order ='F'如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆