Creating a 5x5 array with random values and finding row maximum Indices using NumPy
NumPy: Advanced Exercise-25 with Solution
Write a NumPy program to create a 5x5 array with random values and find the index of the maximum value in each row.
This NumPy program creates a 5x5 array filled with random values and then finds the index of the maximum value in each row. It iterates through each row to determine the index of the maximum value and stores the results in an array.
Sample Solution:
Python Code:
import numpy as np
# Create a 5x5 array with random values
array = np.random.random((5, 5))
# Find the index of the maximum value in each row
max_indices = np.argmax(array, axis=1)
# Print the array and the indices of the maximum values
print("Array:\n", array)
print("Indices of the maximum values in each row:\n", max_indices)
Output:
Array: [[0.03319994 0.87733658 0.15561569 0.09115729 0.50300971] [0.16636484 0.11402533 0.27361528 0.05784223 0.95653183] [0.9419271 0.03121247 0.19712034 0.92254315 0.34829598] [0.87937086 0.50750646 0.40539581 0.82764216 0.01438484] [0.19968155 0.57303488 0.94165787 0.44044397 0.87607812]] Indices of the maximum values in each row: [1 4 0 0 2]
Explanation:
- Import NumPy: Import the NumPy library to work with arrays.
- Create a Random 5x5 Array: Generate a 5x5 array filled with random values using np.random.random.
- Find Indices of Maximum Values: Use np.argmax with axis=1 to find the indices of the maximum values in each row.
- Print Results: Print the generated array and the indices of the maximum values in each row.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Compute the Frobenius norm of a 3x3 random array using NumPy.
Next: Creating a 5x5 srray with random values and finding row minimum Indices using NumPy.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics