Python | Numpy matrix.argmin ()

argmin | NumPy | Python Methods and Functions

Using the Numpy matrix.argmax () method, we can find the index value of the smallest element in a given matrix that has one or more dimensions.

Syntax: matrix.argmin()

Return: Return index number of minimum elements in matrix

Example # 1:
In this example, we see that using the matrix.argmax () we can find the index of the minimum element in the given matrix.

# import important module into python

import numpy as np

# make a matrix with NumPy

gfg = np.matrix ( `[1, 2, 3, 4]` )

# using the matrix.argmin () method

geeks = gfg.argmin ()


print (geeks)

Exit :


Example # 2:

# import an important module into python

import numpy as np

# make a matrix with NumPy

gfg = < code class = "plain"> np.matrix ( `[1, 2, 3; 4, -5, 6; 7, 8, 9] ` )

# using the matrix.argmin () method

geeks = gfg.argmin ()


print (geeks)

Exit :


Python | Numpy matrix.argmin (): StackOverflow Questions

Answer #1

import numpy as np
def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

array = np.random.random(10)
# [ 0.21069679  0.61290182  0.63425412  0.84635244  0.91599191  0.00213826
#   0.17104965  0.56874386  0.57319379  0.28719469]

value = 0.5

print(find_nearest(array, value))
# 0.568743859261

Answer #2

Say that you have a list values = [3,6,1,5], and need the index of the smallest element, i.e. index_min = 2 in this case.

Avoid the solution with itemgetter() presented in the other answers, and use instead

index_min = min(range(len(values)), key=values.__getitem__)

because it doesn"t require to import operator nor to use enumerate, and it is always faster(benchmark below) than a solution using itemgetter().

If you are dealing with numpy arrays or can afford numpy as a dependency, consider also using

import numpy as np
index_min = np.argmin(values)

This will be faster than the first solution even if you apply it to a pure Python list if:

  • it is larger than a few elements (about 2**4 elements on my machine)
  • you can afford the memory copy from a pure list to a numpy array

as this benchmark points out: enter image description here

I have run the benchmark on my machine with python 2.7 for the two solutions above (blue: pure python, first solution) (red, numpy solution) and for the standard solution based on itemgetter() (black, reference solution). The same benchmark with python 3.5 showed that the methods compare exactly the same of the python 2.7 case presented above

Get Solution for free from DataCamp guru