How to find index of Nth element in multidimentional numpy array?

My task is to create random numpy array with shape (2, 3, 2) and find index of the ninth element in it. The answer should be (1, 1, 1). How can I use numpy functionality to do this without using for loops?

Numpy has an unravel_index function which can convert the raveled (flattened) index into the N-d index given the array shape.

import numpy as np

element_number = 9
shape = (2, 3, 2)

index = np.unravel_index(element_number, shape)  # (1, 1, 1)

Leave a Comment