Replace all elements of NumPy array that are greater than some value
I have a 2D NumPy array. How do I replace all values in it greater than a threshold T = 255
with a value x = 255
? A slow for-loop based method would be:
# arr = arr.copy() # Optionally, do not modify original arr.
for i in range(arr.shape[0]):
for j in range(arr.shape[1]):
if arr[i, j] > 255:
arr[i, j] = x
Answers
You can avoid using a slow for
loop by utilizing NumPy's vectorized operations. Here's a faster and more efficient way to replace all values in the 2D array that are greater than a threshold T = 255
with x = 255
:
import numpy as np
# Example array
arr = np.array([[100, 256, 200], [300, 150, 400]])
# Replace values greater than 255 with 255
arr[arr > 255] = 255
print(arr)
Explanation:
arr > 255
creates a boolean mask where values greater than255
areTrue
.arr[arr > 255] = 255
replaces all the values inarr
that areTrue
in the mask with255
.
This method is efficient because it leverages NumPy's ability to perform element-wise operations in bulk without the need for explicit loops.