+5 votes
in Programming Languages by (77.2k points)

I want to print each element of a 2D NumPy array. I do not want to use two "for" loops. Is there any function to iterate over multi-dimensional NumPy arrays?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

The Numpy function nditer() is an efficient multi-dimensional iterator. You can use it to iterate over your 2D NumPy arrays.

Here is an example:

>>> import numpy as np
>>> arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> for v in np.nditer(arr):
...     print(v)
...
1
2
3
4
5
6
7
8
 


...