w3resource

Creating a 5x5 srray with random values and finding row minimum Indices using NumPy

NumPy: Advanced Exercise-26 with Solution

Write a NumPy program to create a 5x5 array with random values and find the index of the minimum 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 minimum value in each row
min_indices = np.argmin(array, axis=1)

# Print the array and the indices of the minimum values
print("Array:\n", array)
print("Indices of the minimum values in each row:\n", min_indices)

Output:

Array:
 [[0.11506035 0.39045454 0.0941495  0.09490619 0.58700996]
 [0.80016435 0.5267106  0.47703409 0.44070748 0.04791699]
 [0.10144517 0.15379856 0.78272377 0.813196   0.00657204]
 [0.51372928 0.57457576 0.41363111 0.64983788 0.89431433]
 [0.17594275 0.74532959 0.37386722 0.20178126 0.3330852 ]]
Indices of the minimum values in each row:
 [2 4 4 2 0]

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 Minimum Values: Use np.argmin with axis=1 to find the indices of the minimum values in each row.
  • Print Results: Print the generated array and the indices of the minimum values in each row.

Python-Numpy Code Editor:

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

Previous: Creating a 5x5 array with random values and finding row maximum Indices using NumPy.
Next:Creating a 3x3 array and computing QR decomposition using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.