w3resource

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

NumPy: Array Object Exercise-120 with Solution

Get Index of Max Element Along Axis

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

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'a' with given elements arranged in 2x3 shape
a = np.array([[1, 2, 3], [4, 3, 11]])

# Printing a message indicating the original array will be displayed
print("Original array:")

# Displaying the original array 'a'
print(a)

# Using np.unravel_index() to get the indices of the maximum element in the array 'a'
# The argmax() function finds the index of the maximum value in the flattened array
# The unravel_index() function converts this flat index into a tuple of indices for the maximum value's position
i, j = np.unravel_index(a.argmax(), a.shape)

# Printing a message indicating the index of the maximum element in the array along one axis
print("Index of a maximum element in a numpy array along one axis:")

# Displaying the indices of the maximum element in the array 'a'
print(i, j) 

Sample Output:

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

Explanation:

a = np.array([[1,2,3],[4,3,1]]): Create a 2D NumPy array a with the given values.

i, j = np.unravel_index(a.argmax(), a.shape): The a.argmax() function returns the index of the maximum value in the flattened array. The np.unravel_index() function converts this index into row and column indices (i, j) corresponding to the original shape of the array.

print(a[i, j]): Print the indices of the maximum value in the array.

Pictorial Presentation:

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

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-120.php