Note: I am not sure if this is a duplicate or not -- please let me know if it is (and close the question).
If one has a 1-dimensional NumPy array vector, then if one writes a for loop of the form:
for element in vector :
print(element)
The result will print each element of the NumPy array.
If one has a 2-dimensional NumPy array matrix, then if one writes a for loop of the form:
for vector in matrix :
print(vector)
The result will print each row of the 2-dimensional NumPy array, i.e. it will print 1-dimensional NumPy arrays, and it will not print each element of the array individually.
However, if one instead writes the for loop as:
import numpy
for element in numpy.nditer(matrix) :
print(element)
The result will print each element of the 2-dimensional NumPy array.
Question: What happens if one has a 3-dimensional NumPy array, tensor?
a. If one writes a for loop of the form:
for unknownType in tensor :
print(unknownType)
Will this print the constituent 2-dimensional NumPy (sub-)arrays of tensor?
I.e. for an n-dimensional NumPy array nArray, does for unknownType in nArray : iterate over the constituent (n-1)-dimensional NumPy (sub-)arrays of nArray?
b. If one writes a for loop of the form:
for unknownType in numpy.nditer(tensor) :
print(unknownType)
Will this print the elements of tensor? Or will it print the constituent 1-dimensional NumPy (sub-)arrays of the constituent 2-dimensional NumPy (sub-)arrays of tensor?
I.e. for an n-dimensional NumPy array nArray, does for unknownType in nditer(nArray) : iterate over the elements of nArray? Or does it iterate over the constituent (n-2)-dimensional NumPy (sub-)arrays of the constituent (n-1)-dimensional NumPy (sub-)arrays of nArray?
It is unclear to me from the name nditer, since I don't know what "nd" stands for ("iter" is obviously short for "iteration"). And presumably one can think of the elements as "0-dimensional NumPy arrays", so the examples given to me for 2-dimensional NumPy arrays are ambiguous.
I've looked at the np.nditer documentation but honestly I didn't understand the examples or what they were trying to demonstrate -- it seems like it was written for programmers (which I am not) by programmers.
nditerisn't of much use in Python level code. Thatnditertutorial is aimed at advanced programmers, especially ones who intend to work withcython.np.ndindexusesnditerto generate indices, and is used innp.vectorizeandnp.apply_along_axis.cythonexample. But if you don't need all the broadcasting help, cython typedmemoryviewsare faster.