4 C
London
Friday, December 20, 2024
HomePandas in PythonGeneral Functions in PythonHow to Replace Elements in NumPy Array (3 Examples)

How to Replace Elements in NumPy Array (3 Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories