Iterate over numpy matrix of unknown dimension

怎甘沉沦 提交于 2019-12-07 16:39:19

问题


I have a multidimensional numpy array I'd like to iterate over. I want to be able to access not only the values, but also their indices. Unfortunately,

for idx,val in enumerate(my_array):

doesn't seem to work when my_array is multidimensional. (I'd like idx to be a tuple). Nested for loops might work, but I don't know the number of dimensions of the array until runtime, and I know it's not appropriate for python anyway. I can think of a number of ways to do this (recursion, liberal use of the % operator), but none of these seem very 'python-esque'. Is there a simple way?


回答1:


I think you want ndenumerate:

>>> import numpy
>>> a = numpy.arange(6).reshape(1,2,3)
>>> a
array([[[0, 1, 2],
        [3, 4, 5]]])
>>> list(numpy.ndenumerate(a))
[((0, 0, 0), 0), ((0, 0, 1), 1), ((0, 0, 2), 2), ((0, 1, 0), 3), ((0, 1, 1), 4), ((0, 1, 2), 5)]


来源:https://stackoverflow.com/questions/11697274/iterate-over-numpy-matrix-of-unknown-dimension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!