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

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

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文档讨论了拆散元素,然后重塑它们的形状。显然,首先完成了。

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

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

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

如何修复AttributeError:模块'numpy'没有属性'square' - python

Improve this question 我已经将numpy更新为1.14.0。我使用Windows10。我尝试运行我的代码,但出现此错误: AttributeError:模块“ numpy”没有属性“ square”这是我的进口商品:%matplotlib inline import matplotlib.pyplot as plt import ten…

numpy.savetxt“元组索引超出范围”? - python

我试图在文本文件中写几行,这是我使用的代码:import numpy as np # Generate some test data data = np.arange(0.0,1000.0,50.0) with file('test.txt', 'w') as outfile: outfile.write('…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。