本文介绍了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)

我知道可以实现此目标的许多方法,但是在将 nditer文档,我似乎找不到使用nditer的解决方案.我以此为契机学习nditer.因此,我宁愿不使用其他解决方案,除非它确实更有效或更有效.

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

这篇关于NumPy:使用nditer迭代numpy数组的外部尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:16