w3resource

NumPy: Replace all elements of NumPy array that are greater than specified array

NumPy: Array Object Exercise-88 with Solution

Write a NumPy program to replace all elements of NumPy array that are greater than the specified array.

Pictorial Presentation:

Python NumPy: Replace all elements of numpy array that are greater than specified array

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' with multiple rows and columns
x = np.array([[ 0.42436315, 0.48558583, 0.32924763],
              [ 0.7439979, 0.58220701, 0.38213418],
              [ 0.5097581, 0.34528799, 0.1563123 ]])

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'x' with its elements
print(x)

# Printing a message indicating the replacement of elements in the array greater than 0.5 with 0.5
print("Replace all elements of the said array with .5 which are greater than .5")

# Replacing all elements in the array 'x' that are greater than 0.5 with the value 0.5
x[x > 0.5] = 0.5

# Printing the modified array 'x' after replacing elements greater than 0.5 with 0.5
print(x)

Sample Output:

Original array:                                                        
[[ 0.42436315  0.48558583  0.32924763]                                 
 [ 0.7439979   0.58220701  0.38213418]                                 
 [ 0.5097581   0.34528799  0.1563123 ]]                                
Replace all elements of the said array with .5 which are greater than .
5                                                                      
[[ 0.42436315  0.48558583  0.32924763]                                 
 [ 0.5         0.5         0.38213418]                                 
 [ 0.5         0.34528799  0.1563123 ]]

Explanation:

The above code demonstrates how to limit the values of a NumPy array based on a condition.

x = np.array(...) – This line ceates a 3x3 NumPy array 'x' with given elements.

x[x > .5] = .5 – This line uses boolean indexing to identify the elements in 'x' that are greater than 0.5. For all elements in 'x' that satisfy this condition, set their values to 0.5.

Python-Numpy Code Editor:

Previous: Write a NumPy program to find unique rows in a NumPy array.
Next: Write a NumPy program to remove specific elements in a NumPy array.

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.