- Функция numpy.argmax() в Python — как использовать
- Что такое функция np.argmax() в Python?
- Синтаксис
- Параметры
- Возвращаемое значение
- Нахождение индекса максимального элемента из одномерного массива
- Нахождение индексов максимальных элементов многомерного массива
- Создание массива с помощью np.arange() и последующее использование np. argmax()
- numpy.argmax#
- Python: как найти индекс максимального значения в списке
- Пример 1: поиск индекса максимального значения в списке
- Пример 2: поиск индекса максимального значения в списке со связями
- 5 Ways to Find the list max index in Python
- 1. Finding max index using for loop
- 2. Using built in methods – max() and index()
- 3. Using enumerate() function to find Python list max index
- 4. Finding max index for multiple occurrences of elements
- 5. Maximum index from a numpy array
Функция numpy.argmax() в Python — как использовать
Функция Numpy argmax() возвращает индексы максимального элемента массива на определенной оси.
Что такое функция np.argmax() в Python?
np.argmax() — это встроенная функция Numpy, которая используется в Python для получения индексов максимального элемента из массива (одномерный массив) или любой строки или столбца (многомерный массив) любого заданного массива.
Синтаксис
Параметры
Функция np.argmax() принимает в качестве параметра три аргумента:
- arr: массив, из которого мы хотим получить индексы максимального элемента.
- axis: по умолчанию это None. Но для многомерного массива, если мы собираемся найти индекс любого максимума элемента по строкам или по столбцам, мы должны указать ось = 1 или ось = 0 соответственно.
- out: это необязательный параметр. Это обеспечивает возможность вставки вывода в массив с соответствующей формой и типом.
Возвращаемое значение
Функция Python NumPy argmax() возвращает массив той же формы, что и заданный массив, содержащий индексы максимальных элементов.
Нахождение индекса максимального элемента из одномерного массива
В этой программе мы сначала объявили массив с некоторыми случайными числами, заданными пользователем. Затем мы напечатали форму (размер) массива.
Затем мы вызвали argmax(), чтобы получить индекс максимального элемента массива. Мы видим, что максимальный элемент этого массива равен 14, что находится в позиции 1, поэтому выход равен 1.
Нахождение индексов максимальных элементов многомерного массива
В приведенной выше программе мы сначала объявили матрицу размера 4 × 3, и вы также можете увидеть форму матрицы, которая равна(4,3). Затем мы вызвали argmax(), чтобы получить вывод о различных случаях.
В первом случае мы передали arr и axis=1, что возвращает массив размера 4, содержащий индексы всех максимальных элементов из каждой строки. Во втором случае мы передали arr и axis=0 , что возвращает массив размера 3.
Создание массива с помощью np.arange() и последующее использование np. argmax()
Давайте воспользуемся функцией numpy arange(), чтобы создать двумерный массив и найти индекс максимального значения массива.
numpy.argmax#
Returns the indices of the maximum values along an axis.
Parameters : a array_like
axis int, optional
By default, the index is into the flattened array, otherwise along the specified axis.
out array, optional
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
keepdims bool, 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.
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.
The maximum value along a given axis.
Convert a flat index into an index tuple.
Apply np.expand_dims(index_array, axis) from argmax to an array as if by calling max.
In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.
>>> 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])
>>> x = np.arange(24).reshape((2, 3, 4)) >>> res = np.argmax(x, axis=1, keepdims=True) >>> res.shape (2, 1, 4)
Python: как найти индекс максимального значения в списке
Вы можете использовать следующий синтаксис, чтобы найти индекс максимального значения списка в Python:
#find max value in list max_value = max(list_name) #find index of max value in list max_index = list_name. index (max_value)
В следующих примерах показано, как использовать этот синтаксис на практике.
Пример 1: поиск индекса максимального значения в списке
Следующий код показывает, как найти максимальное значение в списке вместе с индексом максимального значения:
#define list of numbers x = [9, 3, 22, 7, 15, 16, 8, 8, 5, 2] #find max value in list max_value = max(x) #find index of max value in list max_index = x. index (max_value) #display max value print(max_value) 22 #display index of max value print(max_index) 2
Максимальное значение в списке равно 22 , и мы видим, что оно расположено в списке со значением индекса 2 .
Примечание. В Python значения индекса начинаются с 0.
Пример 2: поиск индекса максимального значения в списке со связями
В следующем коде показано, как найти максимальное значение в списке вместе с индексом максимального значения, когда имеется несколько максимальных значений.
#define list of numbers with multiple max values x = [9, 3, 22, 7, 15, 16, 8, 8, 5, 22] #find max value in list max_value = max(x) #find indices of max values in list indices = [index for index, val in enumerate(x) if val == max_value] #display max value print(max_value) 22 #display indices of max value print(indices) [2, 9]
Максимальное значение в списке равно 22 , и мы видим, что оно встречается при значениях индекса 2 и 9 в списке.
5 Ways to Find the list max index in Python
A list is a data structure in python which is used to store items of multiple data types. Because of that, it is considered to be one of the most versatile data structures. We can store items such as string, integer, float, set, list, etc., inside a given list. A list in python is a mutable data type, which means that even after creating a list its elements can be changed. A list is represented by storing its items inside square brackets ‘[ ]’. We can access list elements using indexing. In this article, we shall be looking into how in a python list, we can find the max index.
1. Finding max index using for loop
Finding the maximum index using a for loop is the most basic approach.
my_list = [10,72,54,25,90,40] max = my_list[0] index = 0 for i in range(1,len(my_list)): if my_list[i] > max: max = my_list[i] index = i print(f'Max index is : ')
Here, we have taken a list named ‘my_list’, which contains a list of integers. We initially take the first element of the list as the maximum element and store the element into ‘max’. Then we take a variable as ‘index’ and store it with the value 0.
After that, we shall iterate a loop from index 1 to the last element of the list. Inside the loop using an if statement, we shall compare the ith element, i.e., the current element of ‘my_list’ with the ‘max’ variable. If the value of the current element happens to be greater than the value of ‘max’, then we shall assign the value of the current element to ‘max’ and the current index to ‘i’. After completion of the for loop, we shall print the value of ‘index’, which will denote the index of the maximum value from the list.
The output is:
An above method is a naive approach. It is for understanding how the maximum element will be found. There are more compact methods, and now we shall be looking into some of them.
2. Using built in methods – max() and index()
We can use python’s inbuilt methods to find the maximum index out of a python list.
The max() method is used to find the maximum value when a sequence of elements is given. It returns that maximum element as the function output. It accepts the sequence as the function argument.
The index() method is used to find the index of a given element from a python list. It accepts the element as an argument and returns the index of that element. In the case of multiple occurrences, it will return the smallest index of that element.
First, we shall use the max() function to find the maximum element from the given list ‘my_list’ and store it in ‘max_item’. Then using the index() function, we shall pass the ‘max_item’ inside the function. Using my_list.index(), we shall return the index of the maximum element and print that.
my_list = [10,72,54,25,90,40] max_item = max(my_list) print(f'Max index is : ')
The output is:
3. Using enumerate() function to find Python list max index
The enumerate() function in python is used to add a counter to an iterable. With the help of enumerate() function, we can find the index of the maximum elements from a list. We shall use list comprehension for storing the index. List comprehension is a way of creating sequences out of already existing sequences.
my_list = [10,72,54,25,90,40] max_item = max(my_list) print([index for index, item in enumerate(my_list) if item == max_item])
Using the max() function, we shall store the value of the maximum element into ‘max_item’. Then, we shall enumerate over my_list and check for which list item the value equals max_item. The index for that element shall be printed as a list item.
The output is:
4. Finding max index for multiple occurrences of elements
If there are multiple occurrences of the maximum element for a list, then we will have to apply a different logic for the same. We will make use of list comprehension to store multiple indexes inside a list.
my_list = [10,72,90,90,54,25,90,40] max_item = max(my_list) index_list = [index for index in range(len(my_list)) if my_list[index] == max_item] print(index_list)
First, using the max() function, we shall find the maximum element from the list. Then, using list comprehension, we shall iterate over the list ‘my_list’, and whenever the item value equals the ‘max_item’, we shall save that index into ‘my_list’. Then, we shall print the ‘index_list’.
The output is:
5. Maximum index from a numpy array
To find the maximum item index using the numpy library. First, we shall import the numpy library. Then, using the array() function, we shall pass the list my_list as an argument inside the numpy array. This shall convert the given list into a numpy array and store it into ‘n’. Then, using the argmax() function, we shall print the index of the maximum item from the numpy array.
import numpy as np my_list = [10,72,54,25,90,40] n = np.array(my_list) print(f'Max index is : ')
The output is:
That wraps up Python List Max Index. If you have any doubts or any thoughts to share, leave them in the comments below.
Until next time, Keep Learning!