NumPy:使用nditer迭代numpy数组的外部尺寸
我无法遍历numpy数组的外轴.
I am unable to iterate over the outer axis of a numpy array.
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. I am using this as an opportunity to learn nditer. So I would prefer not using other solutions, unless it is genuinely more efficient or pythonic.
使用简单的for
控制迭代非常容易:
It's easier to control the iteration with a plain 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
的速度快.
Doing this with nditer
is just plain awkward. Unless you need broadcasting use cython
as described at the end of the page, nditer
does not offer any speed advantages. Even with cython
, I've gotten better speeds with memoryviews
than with nditer
.
查看np.ndindex
.它会创建一个尺寸减小的虚拟数组,并对此进行nditer:
Look at np.ndindex
. It creates a dummy array with reduced dimensions, and does a nditer on that:
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之间的区别: https://stackoverflow.com/a/43005985 /901925
I recently explored the difference between direct iteration and nditer over a 1d structured array: https://stackoverflow.com/a/43005985/901925