Replace all elements of NumPy array that are greater than some value

In this tutorial, we will learn how to replace all elements of NumPy array that are greater than some value? By Pranit Sharma Last updated : May 26, 2023

Problem Statement

Given a NumPy array (one-dimensional or two-dimensional), we have to write a Python program to replace all elements of the given NumPy array that are greater than the specified element/value.

Replacing all elements of NumPy array that are greater than some value

To replace all elements of NumPy array that are greater than the specified element/value, you can simply use the relational operator (>=) with the specified value and value to be replaced. Consider the following code statement for this task:

array_name[array_name >= old_value] = new_value

Let us understand with the help of examples

Example 1: Replacing elements in one-dimensional NumPy array

# Import numpy
import numpy as np

# Creating 1D NumPy array
arr = np.array([10, 20, 30, 10, 40, 10])

# Printing array before replacement
print("Array before replacing the values:\n", arr, "\n")

# Replacing all elements of NumPy array
# that are greater than specified value
arr[arr >= 30] = 99

# Printing array after replacement
print("Array after replacing the values:\n", arr, "\n")

Output

Array before replacing the values:
 [10 20 30 10 40 10] 

Array after replacing the values:
 [10 20 99 10 99 10]

Example 2: Replacing elements in two-dimensional NumPy array

# Import numpy
import numpy as np

# Creating 2D NumPy array
arr = np.array([
    [10, 20, 30], 
    [40, 50, 60], 
    [10, 20, 70], 
    [80, 10, 90]]
    )

# Printing array before replacement
print("Array before replacing the values:\n", arr, "\n")

# Replacing all elements of NumPy array
# that are greater than specified value
arr[arr >= 30] = 99

# Printing array after replacement
print("Array after replacing the values:\n", arr, "\n")

Output

Array before replacing the values:
 [[10 20 30]
 [40 50 60]
 [10 20 70]
 [80 10 90]] 

Array after replacing the values:
 [[10 20 99]
 [99 99 99]
 [10 20 99]
 [99 10 99]]

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.