Python Replace Values In Array Condition

Python Replace Values In Array Condition | In this post, we will discuss how to replace values in an array based on a condition in Python programming language. The elements or values of a NumPy array can be substituted with distinct values based on a necessity or condition. The array components are examined, and if the actual value reaches the given situation it will be substituted with a further value.

To replace elements of an array based on a condition in Python, we can use one of these two different methods:-

  1. By Using Relational operators
  2. By Using numpy.where()

Python Replace Values In Array Condition By Using Relational Operators

Here, we can use Relational operators like ‘>’, ‘<‘, or other functions to replace values in an array.

# Importing Numpy module
import numpy as np

# Creating a 2-D Numpy array
n_arr = np.array([45, 52, 10, 5, 50, 25])
print("Given array: ")
print(n_arr)

print("\nReplace all elements of the array which are greater than 30. to 5.25")
n_arr[n_arr > 30.] = 5.25

print("New array: ")
print(n_arr)

Output:-

Given array:
[45 52 10 5 50 25]

Replace all elements of the array which are greater than 30. to 5.25
New array:
[ 5 5 10 5 5 25]

Python Replace Values In Array Condition By Using numpy.where()

Here, we can use functions like numpy.where() to replace values in an array.

# Importing Numpy module
import numpy as np

# Creating a 2-D Numpy array
n_arr = np.array([[45, 25, 10],
                  [15, 51, 25]])

print("Given array:")
print(n_arr)

print("\nReplace all elements of array which are \
greater than or equal to 25 to 0")
print("Else remains the same")
print(np.where(n_arr >= 25, 0, n_arr))

Output:-

Given array:
[ [45 25 10]
[15 51 25] ]

Replace all elements of array which are greater than or equal to 25 to 0
Else remains the same
[ [ 0 0 10]
[15 0 0] ]

So, here we have learned how to replace values or elements of an array based on conditions in Python Programming Language. Hope you all find it useful. Also see:- Remove special characters from the list, Remove duplicates from the list in Python

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *