w3resource

Advanced NumPy Exercises - Replace the minimum value with 0 in a 5x5 array with random values


Write a NumPy program to create a 5x5 array with random values and replace the minimum value with 0.

Sample Solution:

Python Code:

import numpy as np
# Create a 5x5 array with random values
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
# Find the minimum value in the array
min_val = nums.min()
# Replace the minimum value with 0
nums[nums == min_val] = 0
# Print the updated array
print("\nSaid array after replacing the minimum value with 0:")
print(nums)

Output:

Original array elements:
[[0.66474944 0.22822056 0.94826003 0.42181429 0.92132072]
 [0.7707682  0.92442007 0.34407917 0.91478487 0.71020117]
 [0.61960484 0.81076893 0.64559299 0.86607412 0.45967543]
 [0.42792958 0.6072072  0.72882499 0.08851185 0.18901375]
 [0.45278113 0.67513245 0.22555934 0.64190271 0.94388218]]

Said array after replacing the minimum value with 0:
[[0.66474944 0.22822056 0.94826003 0.42181429 0.92132072]
 [0.7707682  0.92442007 0.34407917 0.91478487 0.71020117]
 [0.61960484 0.81076893 0.64559299 0.86607412 0.45967543]
 [0.42792958 0.6072072  0.72882499 0.         0.18901375]
 [0.45278113 0.67513245 0.22555934 0.64190271 0.94388218]]

Explanation:

In the above exercise -

nums = np.random.rand(5, 5): This line creates a 5x5 NumPy array filled with random numbers between 0 and 1.

min_val = nums.min(): This line finds the minimum value in the nums array using the min method and assigns it to the variable min_val.

nums[nums == min_val] = 0: This code uses NumPy boolean indexing to find all elements in nums that are equal to min_val, and sets their value to 0. This effectively replaces the minimum value in the array with 0.

Python-Numpy Code Editor: