python numpy:How to get index of the maximum on list

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

I make a note.
By using numpy of python library, how to get maximum of list, and how to get index of the maximum on the list.

The point to note is that if you use np.where to get the index of the maximum value, the value will be returned by a tuple format.And tuples are immutable, unlike list(mutable), so they can be a little annoying.

Therefore, depending on the subsequent processing, it may be better to use np.argmax to get the maximum index.If it is a multi-dimensional array instead of a one-dimensional array, use flatten() to flatten the array.

import numpy as np

# sample list
samplelist = [3, 1, 2, 8, 4]

# get maximum on list
value_of_max = np.max(samplelist)
print(value_of_max) # 8

# using np.argmax, get index of the maximum on list
index_of_max_01 = np.argmax(samplelist)
print(index_of_max_01) # 3

# using np.where, get index of the maximum on list
index_of_max_02 = np.where(samplelist == value_of_max)
print(index_of_max_02) # (array([3], dtype=int64),)
print(type(index_of_max_02)) # <class 'tuple'>
print(list(index_of_max_02)) # [array([3], dtype=int64)]
print(list(index_of_max_02)[0][0]) # 3

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.