Home  >  Article  >  Backend Development  >  Find the maximum value of numpy array and its indexing method in python

Find the maximum value of numpy array and its indexing method in python

不言
不言Original
2018-04-17 10:49:595057browse

The following is an article to share with you how to find the maximum value of a numpy array and its indexing method in python. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

In the list list, max(list) can get the maximum value of the list, and list.index(max(list)) can get the index corresponding to the maximum value

But There is no index method for array in numpy. Instead, it is where, which is not found in list.

First of all, we can get the maximum value of the array globally and in each row and column (the same is true for the minimum value)

>>> a = np.arange(9).reshape((3,3))
>>> a
array([[0, 1, 2],
  [9, 4, 5],
  [6, 7, 8]])
>>> print(np.max(a))  #全局最大
8
>>> print(np.max(a,axis=0)) #每列最大
[6 7 8]
>>> print(np.max(a,axis=1)) #每行最大
[2 5 8]

Then use where to get the index of the maximum value. In the return value, the former array corresponds to the number of rows, and the latter corresponds to the number of columns

>>> print(np.where(a==np.max(a)))
(array([2], dtype=int64), array([2], dtype=int64))
>>> print(np.where(a==np.max(a,axis=0)))
(array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))

If there are the same maximum values ​​in the array, where will give all their positions

>>> a[1,0]=8
>>> a
array([[0, 1, 2],
  [8, 4, 5],
  [6, 7, 8]])
>>> print(np.where(a==np.max(a)))
(array([1, 2], dtype=int64), array([0, 2], dtype=int64))

Related recommendations:

How to get the specified row and column of numpy array

How to use numpy to find the maximum and minimum value in the array

The above is the detailed content of Find the maximum value of numpy array and its indexing method in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn