The Usage of Numpy.unravel_index() function

numpy.unravel_ The index () function is used to get the position of an index value of type/group int in a multidimensional array

Grammar:

numpy.unravel_ index(indices, dims)

Take a simple example

Find the index of the largest element of a multidimensional array

A = np.random.randint(1,100,size=(2,3,5))
print(A)
array([[[98, 29, 32, 73, 90],
        [36, 52, 24,  2, 37],
        [66, 80, 23, 29, 98]],

       [[17, 32, 58, 99, 74],
        [53,  3, 20, 48, 28],
        [53,  7, 74, 34, 68]]])

ind_max = np.argmax(A)
print(ind_max)
18


ind_max_src = np.unravel_index(ind_max, A.shape)
print(ind_max_src)
(1, 0, 3)

print(A[ind_max_src])
99

If NP. Unreavel_ The first parameter of index (indexes, DIMS) is an array of int type

Returns the index of the original array corresponding to each element in the array (i.e. the value of the flattern index)

idx = np.unravel_index((0,29),A.shape) 
print(idx)
# (array([0, 1], dtype=int64), array([0, 2], dtype=int64), array([0, 4], dtype=int64))

print(idx[0])
print(idx[1])
print(idx[2])
[0 1]
[0 2]
[0 4]

first_idx = (idx[0][0],idx[1][0],idx[2][0])
print(first_idx)
print(A[first_idx])
(0, 0, 0)
98

Similar Posts: