0

I have a multidimensional array. And I have to iterate via some of its axes. If I needed all axes, I could use nditer, but if I need only the specific ones, I have to do it manually:

my_array = np.arange(3 * 4 * 5).reshape((3, 4, 5))
for i in range(my_array.shape[0]):
    for j in range(my_array.shape[1]):
        print(i, j)
        # Here should be some processing of the 3rd dimension items of the (i,j)

Cannot you advice me a simpler way to do it?

1 Answer 1

1

Consider passing to a single loop, and using ndindex (docs):

my_array = np.arange(3 * 4 * 5).reshape((3, 4, 5))
for ij in np.ndindex(my_array.shape[:2]):
    i,j=ij
    print(i,j)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, comrade! It's just what I need. ^__^
np.ndindex uses nditer. np.ndindex((2,3))._it is an nditer instance. Check the code in index_tricks.py for more details.
yes, that's where the source of ndindex is (link), and I am not surprised that it uses as_strided. Am I missing your point?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.