Home » How to Replace Elements in NumPy Array (3 Examples)

How to Replace Elements in NumPy Array (3 Examples)

by Erma Khan

You can use the following methods to replace elements in a NumPy array:

Method 1: Replace Elements Equal to Some Value

#replace all elements equal to 8 with a new value of 20
my_array[my_array == 8] = 20

Method 2: Replace Elements Based on One Condition

#replace all elements greater than 8 with a new value of 20
my_array[my_array > 8] = 20

Method 3: Replace Elements Based on Multiple Conditions

#replace all elements greater than 8 or less than 6 with a new value of 20
my_array[(my_array > 8) | (my_array 6)] = 20

The following examples show how to use each method in practice with the following NumPy array:

import numpy as np

#create array
my_array = np.array([4, 5, 5, 7, 8, 8, 9, 12])

#view array
print(my_array)

[ 4  5  5  7  8  8  9 12]

Method 1: Replace Elements Equal to Some Value

The following code shows how to replace all elements in the NumPy array equal to 8 with a new value of 20:

#replace all elements equal to 8 with 20
my_array[my_array == 8] = 20

#view updated array
print(my_array)

[ 4  5  5  7 20 20  9 12]

Method 2: Replace Elements Based on One Condition

The following code shows how to replace all elements in the NumPy array greater than 8 with a new value of 20:

#replace all elements greater than 8 with 20
my_array[my_array > 8] = 20

#view updated array
print(my_array)

[ 4  5  5  7  8  8 20 20]

Method 3: Replace Elements Based on Multiple Conditions

The following code shows how to replace all elements in the NumPy array greater than 8 or less than 6 with a new value of 20:

#replace all elements greater than 8 or less than 6 with a new value of 20
my_array[(my_array > 8) | (my_array 6)] = 20

#view updated array
print(my_array)

[20 20 20  7  8  8 20 20]

Additional Resources

The following tutorials explain how to perform other common operations in NumPy:

How to Calculate the Mode of NumPy Array
How to Find Index of Value in NumPy Array
How to Map a Function Over a NumPy Array

Related Posts