How can I get get the position (indices) of the largest value in a multi-dimensional NumPy array?
Trilarion
10.5k9 gold badges62 silver badges103 bronze badges
asked Aug 27, 2010 at 12:46
1
The argmax()
method should help.
Update
(After reading comment) I believe the argmax()
method would work for multi dimensional arrays as well. The linked documentation gives an example of this:
>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3
Update 2
(Thanks to KennyTM’s comment) You can use unravel_index(a.argmax(), a.shape)
to get the index as a tuple:
>>> from numpy import unravel_index
>>> unravel_index(a.argmax(), a.shape)
(1, 0)
answered Aug 27, 2010 at 12:48
Manoj GovindanManoj Govindan
71.6k21 gold badges132 silver badges141 bronze badges
5
(edit) I was referring to an old answer which had been deleted. And the accepted answer came after mine. I agree that argmax
is better than my answer.
Wouldn’t it be more readable/intuitive to do like this?
numpy.nonzero(a.max() == a)
(array([1]), array([0]))
Or,
numpy.argwhere(a.max() == a)
answered Feb 24, 2012 at 12:01
otterbotterb
2,6502 gold badges29 silver badges48 bronze badges
2
You can simply write a function (that works only in 2d):
def argmax_2d(matrix):
maxN = np.argmax(matrix)
(xD,yD) = matrix.shape
if maxN >= xD:
x = maxN//xD
y = maxN % xD
else:
y = maxN
x = 0
return (x,y)
answered Jan 12, 2019 at 22:11
iFederxiFederx
83511 silver badges16 bronze badges
An alternative way is change numpy
array to list
and use max
and index
methods:
List = np.array([34, 7, 33, 10, 89, 22, -5])
_max = List.tolist().index(max(List))
_max
>>> 4
answered Sep 4, 2020 at 20:21
- numpy.argmax(a, axis=None, out=None, *, keepdims=<no value>)[source]#
-
Returns the indices of the maximum values along an axis.
- Parameters:
-
- aarray_like
-
Input array.
- axisint, optional
-
By default, the index is into the flattened array, otherwise
along the specified axis. - outarray, optional
-
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype. - keepdimsbool, optional
-
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.New in version 1.22.0.
- Returns:
-
- index_arrayndarray of ints
-
Array of indices into the array. It has the same shape as a.shape
with the dimension along axis removed. If keepdims is set to True,
then the size of axis will be 1 with the resulting array having same
shape as a.shape.
Notes
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.Examples
>>> a = np.arange(6).reshape(2,3) + 10 >>> a array([[10, 11, 12], [13, 14, 15]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2])
Indexes of the maximal elements of a N-dimensional array:
>>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape) >>> ind (1, 2) >>> a[ind] 15
>>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1
>>> x = np.array([[4,2,3], [1,0,3]]) >>> index_array = np.argmax(x, axis=-1) >>> # Same as np.amax(x, axis=-1, keepdims=True) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1) array([[4], [3]]) >>> # Same as np.amax(x, axis=-1) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1) array([4, 3])
Setting keepdims to True,
>>> x = np.arange(24).reshape((2, 3, 4)) >>> res = np.argmax(x, axis=1, keepdims=True) >>> res.shape (2, 1, 4)
Maybe this can return what you are looking for? It returns the index of the max (
max_xy = np.where(a == a.max() )
Zip the result to get the index as list of tuples:
zip(max_xy[0], max_xy[1]) #=> [(1, 0)]
In case of more than one max: a = np.array([[4,2,3],[4,3,4]])
, it returns #=> [(0, 0), (1, 0), (1, 2)]
To return as a tuple the first maximum found, just fetch the first element of the array:
zip(max_xy[0], max_xy[1])[0] #=> (0, 0)
Время чтения 3 мин.
Функция Numpy argmax() возвращает индексы максимального элемента массива на определенной оси.
Содержание
- Что такое функция np.argmax() в Python?
- Синтаксис
- Параметры
- Возвращаемое значение
- Нахождение индекса максимального элемента из одномерного массива
- Нахождение индексов максимальных элементов многомерного массива
- Создание массива с помощью np.arange() и последующее использование np. argmax()
- Несколько вхождений максимальных значений
np.argmax() — это встроенная функция Numpy, которая используется в Python для получения индексов максимального элемента из массива (одномерный массив) или любой строки или столбца (многомерный массив) любого заданного массива.
Синтаксис
numpy.argmax(arr,axis=None,out=None) |
Параметры
Функция np.argmax() принимает в качестве параметра три аргумента:
- arr: массив, из которого мы хотим получить индексы максимального элемента.
- axis: по умолчанию это None. Но для многомерного массива, если мы собираемся найти индекс любого максимума элемента по строкам или по столбцам, мы должны указать ось = 1 или ось = 0 соответственно.
- out: это необязательный параметр. Это обеспечивает возможность вставки вывода в массив с соответствующей формой и типом.
Возвращаемое значение
Функция Python NumPy argmax() возвращает массив той же формы, что и заданный массив, содержащий индексы максимальных элементов.
Нахождение индекса максимального элемента из одномерного массива
См. следующий код.
#Importing numpy import numpy as np #We will create an 1D array arr = np.array([4, 24, 3, 12, 4, 4]) #Printing the array print(«The array is: «, arr) #Shape of the array print(«Shape of the array is : «, np.shape(arr)) #Now we will print index of max value of this array print(«Index of value of the given array is: «, np.argmax(arr)) |
Выход:
The array is: [ 4 24 3 12 4 4] Shape of the array is : (6,) Index of value of the given array is: 1 |
Объяснение.
В этой программе мы сначала объявили массив с некоторыми случайными числами, заданными пользователем. Затем мы напечатали форму (размер) массива.
Затем мы вызвали argmax(), чтобы получить индекс максимального элемента массива. Мы видим, что максимальный элемент этого массива равен 14, что находится в позиции 1, поэтому выход равен 1.
Нахождение индексов максимальных элементов многомерного массива
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#Importing numpy import numpy as np #We will create a 2D array #Of shape 4×3 arr = np.array([(14, 29, 34),(42, 5, 46),(1, 38, 44),(5, 16, 52)]) #Printing the array print(«The array is: «) print(arr) print(«Shape of the array is: «, np.shape(arr)) #Now we will find the indices of maximum value for some cases #Indices of maximum value of each row a = np.argmax(arr, axis=1) print(«Index of maximum value of each row of the array is: «, a) #Indices of ,aximum value of each column b = np.argmax(arr, axis=0) print(«Index of maximum value of each column of the array is: «, b) |
Выход:
The array is: [[14 29 34] [42 5 46] [ 1 38 44] [ 5 16 52]] Shape of the array is: (4, 3) Index of maximum value of each row of the array is: [2 2 2 2] Index of maximum value of each column of the array is: [1 2 3] |
Объяснение.
В приведенной выше программе мы сначала объявили матрицу размера 4 × 3, и вы также можете увидеть форму матрицы, которая равна(4,3). Затем мы вызвали argmax(), чтобы получить вывод о различных случаях.
В первом случае мы передали arr и axis=1, что возвращает массив размера 4, содержащий индексы всех максимальных элементов из каждой строки. Во втором случае мы передали arr и axis=0 , что возвращает массив размера 3.
Создание массива с помощью np.arange() и последующее использование np. argmax()
Давайте воспользуемся функцией numpy arange(), чтобы создать двумерный массив и найти индекс максимального значения массива.
# app.py import numpy as np data = np.arange(8).reshape(2, 4) print(data) maxValIndex = np.argmax(data) print(‘The index of maxium array value is: ‘) print(maxValIndex) |
Выход:
python3 app.py [[0 1 2 3] [4 5 6 7]] The index of maxium array value is: 7 |
Несколько вхождений максимальных значений
В случае многократного вхождения максимальных значений возвращаются индексы, соответствующие первому вхождению.
См. следующий код.
# app.py import numpy as np data = [[21, 11, 10], [18, 21, 19]] print(data) maxValIndex = np.argmax(data) print(‘The index of maxium array value is: ‘) print(maxValIndex) |
Выход:
python3 app.py [[21, 11, 10], [18, 21, 19]] The index of maxium array value is: 0 |
В приведенном выше примере максимальное значение равно 21, но оно встречается в массиве два раза. Таким образом, он вернет индекс первого вхождения. В нашем случае индекс равен 0.
Найдем максимальное значение по заданной оси.
См. следующий код.
# app.py import numpy as np data = [[21, 11, 10], [18, 21, 19]] print(data) maxValIndex = np.argmax(data, axis=0) print(‘The index of maxium array value is: ‘) print(maxValIndex) |
Выход:
python3 app.py [[21, 11, 10], [18, 21, 19]] The index of maxium array value is: [0 1 1] |
В приведенном выше коде мы проверяем максимальный элемент вместе с осью x. Наш вывод — [0, 1, 1], что означает 21 > 18, поэтому он возвращает 0, потому что индекс 21 равен 0. Тогда 11 < 21 означает, что возвращен индекс 21, что равно 1. Тогда 10 < 19, что означает, что вернулся индекс 19, который равен 1.
In this post, we are going to learn how to find the max value index in the NumPy array.The numpy.amax() and np.argmax() function row-wise and column-wise by the help of Python program.
numpy.amax( )
The NumPy module amax() function returns the maximum value of the numpy array or maximum value along an axis.
Syntax
numpy.amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Parameters
- array: The numpy array in which maximum value need to find.
- axis : The optional parameter,if not provided it flatten the array and returns the max value.
- axis =0 returns an array that contain max value for each columns.
- axis=1 returns an array that contain max value for each rows.
1. Find max value Index in 1D NumPy array
In this Python program example, we have used numpy.amax() function to get maximum value by passing a numpy array as an argument. The np. where() function To get the indices of max values that returns tuples of the array that contain indices(one for each axis), wherever max value exists. We can access indices by using indices[0].
import numpy as np nparr = np.array([3,6,9,12,15,18,21,24,27,30,9,9,9]) indice = np.where(nparr == np.amax(nparr)) print('max value index:',indice) print('max value index:',indice[0])
Output
indices: (array([9], dtype=int32),) max value index: [9]
2. Find max value index in 2D NumPy array
In this Python program example,we are finding max value in 2D NumPy array.numpy.amax() return the max value in 2D array.The numpy.where(condition) will return a tuple of two arrays indexes of max values.
- In which the first array tuples contain row-wise indices for max values.
- The second array tuple for column-wise indices for max values.
- The zip() function to zip both arrays to get all indices row-wise and column-wise.
- The for loop to iterate over the zip arrays.
import numpy as np nparr = np.array([[3, 6, 9], [12, 9, 18], [21,9, 3], [6,9 , 12]]) maxvalInCols = np.amax(nparr, axis=0) print('max values colwise:',maxvalInCols) maxvalInRows = np.amax(nparr, axis=1) print('max values Rowswise:',maxvalInRows) #rows-columns max values indices index = np.where(nparr == np.amax(nparr)) print(index) listofIndices = list(zip(index[0], index[1])) for indexes in listofIndices: print('indices of max vaues:',indexes)
Output
max values colwise : [21 9 18] max values Rowswise: [ 9 18 21 12] (array([2], dtype=int32), array([0], dtype=int32)) indices of max vaues: (2, 0)
3. numpy argmax() 2D to Find max value index column-wise
In this Python example, we have used numpy.amax() function with axis=0 to get all the max values column-wise.To get the indices of all max values column-wise, We have used np. argmax() function that accepts two arguments numpy array along with axis.
import numpy as np nparr = np.array([[3, 6, 9], [12, 9, 18], [21,9, 3], [6,9 , 12]]) #column wise max values and indexes max_val_colwise = np.amax(nparr, axis=0) print('max val column-wise:',max_val_colwise) #column wise max values indexes maxVal_Index_colwise = np.argmax(nparr, axis=0) print('max val index colwise:',maxVal_Index_colwise)
Output
max val column-wise: [21 9 18] max val index colwise: [2 1 1]
4. numpy argmax 2D to Find Max value index row-wise
In this Python example, we have used amax() function with axis=1 to get all the max values row-wise.To get the indices of all max values row-wise, We have used the np.argmax() function that accepts a two-dimensional numpy array along with an axis.
import numpy as np nparr = np.array([[3, 6, 9], [12, 9, 18], [21,9, 3], [6,9 , 12]]) #row wise max values and indexes maxVal_ind_rowise = np.argmax(nparr, axis=1) print('max val rowise:',max_val_Rowwise) #row wise max values indexes max_val_Rowwise = np.amax(nparr, axis=1) print('max val index rowise:',maxVal_ind_rowise)
Output
max val index rowise: [ 9 18 21 12] max val index rowise: [2 2 0 2]
5. NumPy max() with NAN value
The NumPy amax() function returns NAN values as the maximum value in the case of a numpy array containing NAN values. Let us understand with an example.
import numpy as np nparr = np.array([3, 6, 9, 12, 15,np.nan], dtype=float) print(nparr) maxVal_Index = np.argmax(nparr) print('max value in array: ', np.amax(nparr)) print('max value index: ', maxVal_Index)
Output
[ 3. 6. 9. 12. 15. nan] max value in array: nan max value index: 5
Summary
In this post we have learned how to how to Find max value index in NumPy array by using numpy.amax() and np.argmax() function