4

我有一个 2D 数组,我正在迭代它以使用索引值进行计算,然后将计算值分配给所述索引。

在 NumPy 文档中,提供了一个使用迭代器修改值的示例:

for x in np.nditer(a, op_flags=['readwrite']):
    x[...] = 2 * x

但是,使用以下方法跟踪索引时,这似乎不起作用:

it = np.nditer(a, flags=['multi_index'])
while not it.finished:
    it[...] = . . .
    it.iternext()

但是,我能够使用这些it.multi_index值,但它似乎不必要地冗长。有没有更简单的方法来实现这一点,或者通过不同的方法或不同的语法?

it = np.nditer(a, flags=['multi_index'])
while not it.finished:
    matrix[it.multi_index[0]][it.multi_index[1]] = . . .
    it.iternext()

编辑

这是multi_index尝试使用迭代器索引修改值并失败的迭代示例。

matrix = np.zeros((5,5))
it = np.nditer(matrix, flags=['multi_index'])
while not it.finished:
  it[...] = 1
  it.iternext()

产生的错误是

TypeError                                 Traceback (most recent call last)
<ipython-input-79-3f4cabcbfde6> in <module>()
     25 it = np.nditer(matrix, flags=['multi_index'])
     26 while not it.finished:
---> 27   it[...] = 1
     28   it.iternext()

TypeError: invalid index type for iterator indexing
4

1 回答 1

6

在您的第一个迭代示例中:

In [1]: arr = np.arange(12).reshape(3,4)
In [2]: for x in np.nditer(arr, op_flags=['readwrite']):
   ...:     print(x, type(x))
   ...:     x[...] = 2 * x
   ...:     
0 <class 'numpy.ndarray'>
1 <class 'numpy.ndarray'>
2 <class 'numpy.ndarray'>
3 <class 'numpy.ndarray'>
4 <class 'numpy.ndarray'>
....
11 <class 'numpy.ndarray'>
In [3]: x
Out[3]: array(22)
In [4]: arr
Out[4]: 
array([[ 0,  2,  4,  6],
       [ 8, 10, 12, 14],
       [16, 18, 20, 22]])

开启多索引:

In [9]: it = np.nditer(arr, flags=['multi_index'],op_flags=['readwrite'])
In [10]: while not it.finished:
    ...:     print(it[0], it.multi_index)
    ...:     it.iternext()
    ...:     
0 (0, 0)
2 (0, 1)
4 (0, 2)
...
20 (2, 2)
22 (2, 3)

通过 的元素进行相同的迭代arr,但也生成 2d 索引元组。itnditer对象,具有各种方法和属性。在这种情况下,它有一个multi_index属性。并且当前迭代变量在it[0].

我可以使用[...]就地修改元素,也可以通过索引来修改元素arr

In [11]: it = np.nditer(arr, flags=['multi_index'],op_flags=['readwrite'])
In [13]: while not it.finished:
    ...:     it[0][...] *= 2
    ...:     arr[it.multi_index] += 100
    ...:     it.iternext()
    ...:     

In [14]: arr       # values are doubled and add by 100
Out[14]: 
array([[100, 104, 108, 112],
       [116, 120, 124, 128],
       [132, 136, 140, 144]])

没有multi_index我仍然可以创建一个对象,并使用语法nditer进行迭代。while not finished而不是访问x[...]我必须使用it[0][...].


np.ndindex是一种更方便的生成multi_index. 看它的代码。它是少数使用np.nditer.

In [26]: for idx in np.ndindex(arr.shape):
    ...:     print(idx)
    ...:     arr[idx] -= 100
    ...:     
(0, 0)
(0, 1)
...
(2, 3)
In [27]: arr
Out[27]: 
array([[ 0,  4,  8, 12],
       [16, 20, 24, 28],
       [32, 36, 40, 44]])

虽然玩起来很有趣nditer,但它并不实用,至少在纯 Python 代码中不实用。cython作为在或纯c代码中使用它的垫脚石,它是最有用的。请参阅迭代页面的最后一个示例。

于 2018-02-12T02:00:48.847 回答