w3resource

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

NumPy: Advanced Exercise-13 with Solution

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

Sample Solution:

Python Code:

import numpy as np
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
max_value = np.max(nums)
nums[nums == max_value] = 0
print("\nSaid array after replacing the maximum value with 0:")
print(nums)

Sample Output:

Original array elements:
[[0.08108911 0.90790852 0.49904933 0.43776596 0.89029335]
 [0.79855849 0.56237809 0.41445277 0.76242605 0.65669202]
 [0.49775558 0.15230577 0.432398   0.28718127 0.34919357]
 [0.70245807 0.91730805 0.83643487 0.88097636 0.58388187]
 [0.03814885 0.1941247  0.11490991 0.86694541 0.52503499]]

Said array after replacing the maximum value with 0:
[[0.08108911 0.90790852 0.49904933 0.43776596 0.89029335]
 [0.79855849 0.56237809 0.41445277 0.76242605 0.65669202]
 [0.49775558 0.15230577 0.432398   0.28718127 0.34919357]
 [0.70245807 0.         0.83643487 0.88097636 0.58388187]
 [0.03814885 0.1941247  0.11490991 0.86694541 0.52503499]]

Explanation:

nums = np.random.rand(5, 5)  -> Creates a 5x5 array nums with random values using np.random.rand().

max_value = np.max(nums)  -> We find the maximum value in the array using np.max(nums). This value is stored in the max_value variable.

nums[nums == max_value] = 0

In the above code we use boolean indexing to find all the elements in the nums array that are equal to the max_value, i.e., nums == max_value. This creates a boolean mask of the same shape as nums.

Finally, we use this boolean mask to replace all the elements in nums that are equal to max_value with 0. This is done using the code nums[nums == max_value] = 0.

Python-Numpy Code Editor:

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

Previous: Find the second-largest value in each column in an array.
Next: Replace the minimum value with 0 in a 5x5 array with random values.

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.