2017-03-25 51 views
0

我无法迭代numpy数组的外部轴。NumPy:使用nditer遍历numpy数组的外部维数

import numpy as np 

a = np.arange(2*3).reshape(2,3) 
it = np.nditer(a) 
for i in it: 
    print i 

这给了,正如人们所预料:

0 
1 
2 
3 
4 
5 

我会的,不过,像输出到接二连三,这样,我遍历外轴:

(0, 1, 2) 
(3, 4, 5) 

我知道有很多方法可以实现这个目标,但是在浇铸完nditer documentation后,我似乎无法找到使用nditer的解决方案。我以此为契机学习nditer。所以我宁愿不使用其他解决方案,除非它真的更高效或pythonic。

+1

尝试评论'it = np.nditer(a)'行 – ZdaR

+0

我以此为例来学习nditer。我知道我可以使用“为我在:” – shrokmel

回答

1

它很容易与普通for控制迭代:

In [17]: a 
Out[17]: 
array([[0, 1, 2], 
     [3, 4, 5]]) 
In [18]: for row in a: 
    ...:  print(row) 
    ...:  
[0 1 2] 
[3 4 5] 

nditer这样做,只是普通的尴尬。除非您需要使用页面末尾所述的cython广播,否则nditer不提供任何速度优势。即使使用cython,我的memoryviews的速度也比nditer的速度更快。

看看np.ndindex。它创建尺寸减小的虚拟阵列,并且确实在一个nditer:

In [20]: for i in np.ndindex(a.shape[0]): 
    ...:  print(a[i,:]) 
    ...:  
[[0 1 2]] 
[[3 4 5]] 

明白了:

In [31]: for x in np.nditer(a.T.copy(), flags=['external_loop'], order='F'): 
    ...:  print(x) 

[0 1 2] 
[3 4 5] 

就像我说的 - 尴尬

我最近探讨直接迭代之间的区别和nditer在一个1d结构化数组:https://stackoverflow.com/a/43005985/901925

+0

完美!正是我想知道的。我错误地认为nditer会给我速度优势。是的,这是尴尬和不必要的。正式注意!谢谢@hpaulj – shrokmel

0

你可以迭代它,就像迭代一维数组来获得你想要的输出一样。

for k,v in enumerate(a): 
     print(v) 
+0

谢谢!正如我所说,我知道有很多这样做的方式,包括这个。在你的答案中,你甚至可以摆脱枚举,得到相同的结果。我正在寻找使用nditer的答案。 – shrokmel

+0

,因为它在numpy nditer文档中提到,“nditer取代了flatiter。”https://docs.scipy.org/doc/numpy/reference/generated/numpy.flatiter.html#numpy.flatiter –

+0

可以请你描述什么是你想做什么? –