简体   繁体   English

NumPy:使用nditer迭代numpy数组的外部尺寸

[英]NumPy: iterate over outer dimension of numpy array using nditer

I am unable to iterate over the outer axis of a numpy array. 我无法遍历numpy数组的外轴。

import numpy as np

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

and this gives, as one would expect: 正如人们所期望的那样:

0
1
2
3
4
5

I would, however, like the output to come in threes, such that I have iterated over the outer axes: 但是,我希望输出为三分之二,这样就可以遍历外轴:

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

I know of many ways in which I can achieve this, but after pouring over the nditer documentation , I can't seem to find a solution using nditer. 我知道有许多方法可以实现这一目标,但是在仔细阅读nditer文档之后 ,我似乎找不到使用nditer的解决方案。 I am using this as an opportunity to learn nditer. 我以此为契机学习nditer。 So I would prefer not using other solutions, unless it is genuinely more efficient or pythonic. 因此,我宁愿不使用其他解决方案,除非它确实更有效或更有效。

It's easier to control the iteration with a plain for : 用一个简单的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]

Doing this with nditer is just plain awkward. nditer这样做很尴尬。 Unless you need broadcasting use cython as described at the end of the page, nditer does not offer any speed advantages. 除非您需要如页面末尾所述使用cython广播, nditer不会提供任何速度优势。 Even with cython , I've gotten better speeds with memoryviews than with nditer . 即使使用cython ,使用cython速度memoryviews比使用nditer

Look at np.ndindex . np.ndindex It creates a dummy array with reduced dimensions, and does a nditer on that: 它创建一个尺寸减小的虚拟数组,并对此进行nditer:

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

Got it: 得到它了:

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

[0 1 2]
[3 4 5]

Like I said - awkward 就像我说的-尴尬

I recently explored the difference between direct iteration and nditer over a 1d structured array: https://stackoverflow.com/a/43005985/901925 我最近探讨了在一维结构化数组上直接迭代与nditer之间的区别: https ://stackoverflow.com/a/43005985/901925

You can iterate it over just like you iterate over a 1D array to get the output like you want. 您可以像迭代一维数组那样迭代它,以获取所需的输出。

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

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

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