nditer —— numpy.ndarray 多维数组的迭代

1. Single array iteration

>>> a = np.arange(6).reshape(2,3)
>>> for x in np.nditer(a):
...     print x,
...
0 1 2 3 4 5
  • 也即默认是行序优先(row-major order,或者说是 C-order),这样迭代遍历的目的在于,实现和内存分布格局的一致性,以提升访问的便捷性;
>>> for x in np.nditer(a.T):
...     print x,
...
0 1 2 3 4 5
>>> for x in np.nditer(a.T.copy(order='C')):
...     print x,
...
0 3 1 4 2 5
  • 也即对 aa.T 的遍历执行的是同意顺序,也即是它们在内存中的实际存储顺序。

2. 控制遍历顺序

  • for x in np.nditer(a, order='F'):Fortran order,也即是列序优先;
  • for x in np.nditer(a.T, order='C'):C order,也即是行序优先;

3. 修改数组中元素的值

默认情况下,nditer将视待迭代遍历的数组为只读对象(read-only),为了在遍历数组的同时,实现对数组元素值得修改,必须指定 read-write 或者 write-only的模式。

>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> for x in np.nditer(a, op_flags=['readwrite']):
...     x[...] = 2 * x
...
>>> a
array([[ 0,  2,  4],
       [ 6,  8, 10]])

4. 使用外部循环

将一维的最内层的循环转移到外部循环迭代器,使得 numpy 的矢量化操作在处理更大规模数据时变得更有效率。

>>> a = np.arange(6).reshape(2,3)
>>> for x in np.nditer(a, flags=['external_loop']):
...     print x,
...
[0 1 2 3 4 5]
>>>
>>> for x in np.nditer(a, flags=['external_loop'], order='F'):
...     print x,
...
[0 3] [1 4] [2 5]

5. 追踪单个索引或多重索引(multi-index)

>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> it = np.nditer(a, flags=['f_index'])
>>> while not it.finished:
...     print "%d <%d>" % (it[0], it.index),
...     it.iternext()
...
0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5>
            # 索引的编号,以列序优先
>>> it = np.nditer(a, flags=['multi_index'])
>>> while not it.finished:
...     print "%d <%s>" % (it[0], it.multi_index),
...     it.iternext()
...
0 <(0, 0)> 1 <(0, 1)> 2 <(0, 2)> 3 <(1, 0)> 4 <(1, 1)> 5 <(1, 2)>

references

原文地址:https://www.cnblogs.com/mtcnn/p/9422233.html