NumPy: Replace all numbers in a given array which is equal, less and greater to a given number
Replace Numbers Based on Condition
Write a NumPy program to replace all numbers in a given array equal, less and greater than a given number.
This problem involves writing a NumPy program to replace all numbers in a given array that are equal to, less than, and greater than a given number. The task requires utilizing NumPy's array manipulation capabilities, such as boolean indexing and conditional assignment, to efficiently replace elements based on the specified conditions. By applying conditional replacement techniques, the program modifies the original array to replace elements that meet the specified criteria, providing flexibility in data manipulation for various analytical tasks.
Sample Solution:
Python Code :
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'nums' containing values in a 3x3 matrix
nums = np.array([[5.54, 3.38, 7.99],
[3.54, 8.32, 6.99],
[1.54, 2.39, 9.29]])
# Printing a message indicating the original array
print("Original array:")
print(nums)
# Assigning values to variables 'n' and 'r'
n = 8.32
r = 18.32
# Printing a message indicating the replacement of elements equal to 'n' with 'r'
print("\nReplace elements of the said array which are equal to", n, "with", r)
print(np.where(nums == n, r, nums))
# Printing a message indicating the replacement of elements less than 'n' with 'r'
print("\nReplace elements of the said array which are less than", n, "with", r)
print(np.where(nums < n, r, nums))
# Printing a message indicating the replacement of elements greater than 'n' with 'r'
print("\nReplace elements of the said array which are greater than", n, "with", r)
print(np.where(nums > n, r, nums))
Output:
Original array: [[5.54 3.38 7.99] [3.54 8.32 6.99] [1.54 2.39 9.29]] Replace elements of the said array which are equal to 8.32 with 18.32 [[ 5.54 3.38 7.99] [ 3.54 18.32 6.99] [ 1.54 2.39 9.29]] Replace elements with of the said array which are less than 8.32 with 18.32 [[18.32 18.32 18.32] [18.32 8.32 18.32] [18.32 18.32 9.29]] Replace elements with of the said array which are greater than 8.32 with 18.32 [[ 5.54 3.38 7.99] [ 3.54 8.32 6.99] [ 1.54 2.39 18.32]]
Explanation:
In the above code –
np.array(...): Creates a 3x3 NumPy array with the given values and stores in a variable ‘nums’.
n = 8.32 and r = 18.32: Set the variables n and r to 8.32 and 18.32, respectively.
np.where(nums == n, r, nums): This statement uses np.where() to create a new array with the same shape as nums. For each element in nums, if the element is equal to n (8.32), the new array will have the value r (18.32) at the corresponding position; otherwise, the new array will have the same value as in nums.
Python-Numpy Code Editor:
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