w3resource

NumPy: Get the index of a maximum element in a numpy array along one axis

NumPy: Array Object Exercise-120 with Solution

Write a NumPy program to get the index of a maximum element in a numpy array along one axis.

Sample Solution:

Python Code:

import numpy as np    
a = np.array([[1,2,3],[4,3,1]])
print("Original array:")
print(a)
i,j = np.unravel_index(a.argmax(), a.shape)
print("Index of a maximum element in a numpy array along one axis:")
print(a[i,j])

Sample Output:

Original array:
[[1 2 3]
 [4 3 1]]
Index of a maximum element in a numpy array along one axis:
4

Pictorial Presentation:

Python NumPy: Get the index of a maximum element in a numpy array along one axis

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to add a new row to an empty numpy array.
Next: Write a NumPy program to join a sequence of arrays along a new axis.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]