Is it possible to find the index of the 100th element? I have created a random array using NumPy’s function. Now, my target is to find the index of the 100th element of my array. I’m using the code below but it is showing an error.

import numpy as np
# create a 3-dimensional array of shape (10, 10, 10)
arr = np.arange(1000).reshape((10, 10, 10))
indices = np.argpartition(arr.flatten(99))
index = np.unravel_index(indices[-1], arr.shape)
print(index)
TypeError Traceback (most recent call last)
<ipython-input-10-7440658048f3> in <cell line: 5>()
3 arr = np.arange(1000).reshape((10, 10, 10))
4 # find the index of the 100th element using argpartition function
----> 5 indices = np.argpartition(arr.flatten(99))
6 index = np.unravel_index(indices[-1], arr.shape)
7 print(index)
TypeError: order must be str, not int

Is there any way of finding the index of the 100th element?

Hey @safa, you can use the argsort() function in NumPy. As is used to perform an indirect sort on an input array, which means it returns an array of indices that would sort the input array. It takes an array as input and returns an array of indices that would sort the input array along the specified axis.

For example, to find the index (x,y,z) of the 100th element is by using the argsort() function.

Yes, there are methods for doing this task, the method I use involves using the argpartition() function which is used to find the index of a specified element, simply pass the array and the index of the element you want to find and it returns the indices that would partition the array into the desired order. For example:

After finding indices, we then take the first 100 indices using slicing, and find the index of the last element in the resulting array using the unravel_index() function.

unravel_index(indices, shape) function that takes an array of flat indices and returns the corresponding tuple of multidimensional indices. This gives you the index of the 100th element in the array.