I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray named arr, you can replace all elements >255 with a value x as follows:

arr[arr > 255] = x

I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.

In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop
Answer from mdml on Stack Overflow
🌐
ProjectPro
projectpro.io › recipes › replace-items-that-satisfy-condition-with-another-value-numpy-array
How to Replace Values in a NumPy Array? -
May 16, 2024 - Begin by importing the NumPy library. Create a sample 2D array for demonstration purposes. Access the element using its row and column indices and assign a new value to replace a specific value.
Top answer
1 of 8
479

I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray named arr, you can replace all elements >255 with a value x as follows:

arr[arr > 255] = x

I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.

In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop
2 of 8
64

If you want a new array result containing a copy of arr whenever arr < 255, and 255 otherwise:

result = np.minimum(arr, 255)

More generally, for a lower and/or upper bound:

result = np.clip(arr, 0, 255)

If you just want to access the values over 255, or something more complicated, @mtitan8's answer is more general, but np.clip and np.minimum (or np.maximum) are nicer and much faster for your case:

In [292]: timeit np.minimum(a, 255)
100000 loops, best of 3: 19.6 µs per loop

In [293]: %%timeit
   .....: c = np.copy(a)
   .....: c[a>255] = 255
   .....: 
10000 loops, best of 3: 86.6 µs per loop

If you want to do it in-place (i.e., modify arr instead of creating result) you can use the out parameter of np.minimum:

np.minimum(arr, 255, out=arr)

or

np.clip(arr, 0, 255, arr)

(the out= name is optional since the arguments in the same order as the function's definition.)

For in-place modification, the boolean indexing speeds up a lot (without having to make and then modify the copy separately), but is still not as fast as minimum:

In [328]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: np.minimum(a, 255, a)
   .....: 
100000 loops, best of 3: 303 µs per loop

In [329]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: a[a>255] = 255
   .....: 
100000 loops, best of 3: 356 µs per loop

For comparison, if you wanted to restrict your values with a minimum as well as a maximum, without clip you would have to do this twice, with something like

np.minimum(a, 255, a)
np.maximum(a, 0, a)

or,

a[a>255] = 255
a[a<0] = 0
Discussions

python - How to replace values in a numpy array? - Data Science Stack Exchange
I'm learning how to implement and evaluate a Logistic Regression Model, for this I need to change the values of my array from strings to 0 & 1. I have the following numpy ndarray as a result of a More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
January 7, 2021
python - Fast replacement of values in a numpy array - Stack Overflow
I have a very large numpy array (containing up to a million elements) like the one below: [0,1,6,5,1,2,7,6,2,3,8,7,3,4,9,8,5,6,11,10,6,7,12,11,7, 8,13,12,8,9,14,13,10,11,16,15,11,12,17,16,12,13,18,... More on stackoverflow.com
🌐 stackoverflow.com
Replace elements in numpy array
Figured it out! Much simpler than I thought. If CARD_DIR is a np.array (maybe even a list or tuple?) you can just subset it with the array of indices. dir_as_str = CARD_DIR[index_arr] It was that easy! I was aware of this behavior with boolean arrays, but didn't realize you could do this with arrays of integers acting as indices. More on reddit.com
🌐 r/learnpython
3
1
September 9, 2021
python - How to replace values in numpy array at the same time - Stack Overflow
I have numpy array with random numbers. For example like this [7 1 2 0 2 3 4 0 5] and I want to replace every number at the same time if number from this array = 7, I want to replace it with 2 , al... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Statology
statology.org › home › how to replace elements in numpy array (3 examples)
How to Replace Elements in NumPy Array (3 Examples)
March 30, 2025 - You can use the following methods to replace elements in a NumPy array: ... #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
🌐
GeeksforGeeks
geeksforgeeks.org › python › replace-numpy-array-elements-that-doesnt-satisfy-the-given-condition
Replace NumPy Array Elements that doesn't Satisfy the Given Condition - GeeksforGeeks
October 9, 2025 - If elements in a NumPy array don’t meet a certain condition, you replace them with another value (like 0, -1, or NaN), while keeping the elements that satisfy the condition unchanged.
🌐
Python Guides
pythonguides.com › python-numpy-replace
Replace Values In NumPy Array By Index In Python
May 16, 2025 - When you need to replace multiple consecutive values, slicing is the way to go. It’s efficient and maintains the readability of your code. import numpy as np # Create a sample array of monthly website visitors (in thousands) visitors = np.array([45, 48, 52, 49, 53, 57, 60, 58, 56, 59, 62, 65]) # Replace values for summer months (indices 5, 6, 7) with higher numbers visitors[5:8] = [70, 75, 72] print(visitors)
🌐
Delft Stack
delftstack.com › "delft stack" › "howto" › "python numpy howtos" › "how to replace values in numpy"
How to Replace Values in NumPy | Delft Stack
February 2, 2024 - To replace values in a NumPy array, use numpy.clip() or combine numpy.minimum() and numpy.maximum() to clamp values between two limits. For a condition such as “replace every value above 5,” use boolean indexing and assignment.
Find elsewhere
🌐
Finxter
blog.finxter.com › 5-efficient-ways-to-replace-values-in-python-numpy-arrays
5 Efficient Ways to Replace Values in Python Numpy Arrays – Be on the Right Side of Change
This example demonstrates np.copyto where it parses the array, condition, and the value to copy. The where parameter holds the condition for replacement making the operation efficient and compact. Method 1: Basic Indexing. Intuitive and easy to implement. May not be the most efficient for large data sets or complex conditions. Method 2: Using np.where. Versatile and optimized for performance. Might be overkill for simple replacement needs. Method 3: Vectorized Operations. Leveraging Numpy’s speed for large arrays.
Top answer
1 of 11
49

I believe there's even more efficient method, but for now, try

from numpy import copy

newArray = copy(theArray)
for k, v in d.iteritems(): newArray[theArray==k] = v

Microbenchmark and test for correctness:

#!/usr/bin/env python2.7

from numpy import copy, random, arange

random.seed(0)
data = random.randint(30, size=10**5)

d = {4: 0, 9: 5, 14: 10, 19: 15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}
dk = d.keys()
dv = d.values()

def f1(a, d):
    b = copy(a)
    for k, v in d.iteritems():
        b[a==k] = v
    return b

def f2(a, d):
    for i in xrange(len(a)):
        a[i] = d.get(a[i], a[i])
    return a

def f3(a, dk, dv):
    mp = arange(0, max(a)+1)
    mp[dk] = dv
    return mp[a]


a = copy(data)
res = f2(a, d)

assert (f1(data, d) == res).all()
assert (f3(data, dk, dv) == res).all()

Result:

$ python2.7 -m timeit -s 'from w import f1,f3,data,d,dk,dv' 'f1(data,d)'
100 loops, best of 3: 6.15 msec per loop

$ python2.7 -m timeit -s 'from w import f1,f3,data,d,dk,dv' 'f3(data,dk,dv)'
100 loops, best of 3: 19.6 msec per loop
2 of 11
29

Assuming the values are between 0 and some maximum integer, one could implement a fast replace by using the numpy-array as int->int dict, like below

mp = numpy.arange(0,max(data)+1)
mp[replace.keys()] = replace.values()
data = mp[data]

where first

data = [ 0  1  6  5  1  2  7  6  2  3  8  7  3  4  9  8  5  6 11 10  6  7 12 11  7
  8 13 12  8  9 14 13 10 11 16 15 11 12 17 16 12 13 18 17 13 14 19 18 15 16
 21 20 16 17 22 21 17 18 23 22 18 19 24 23]

and replacing with

replace = {4: 0, 9: 5, 14: 10, 19: 15, 20: 0, 21: 1, 22: 2, 23: 3, 24: 0}

we obtain

data = [ 0  1  6  5  1  2  7  6  2  3  8  7  3  0  5  8  5  6 11 10  6  7 12 11  7
  8 13 12  8  5 10 13 10 11 16 15 11 12 17 16 12 13 18 17 13 10 15 18 15 16
  1  0 16 17  2  1 17 18  3  2 18 15  0  3]
🌐
Reddit
reddit.com › r/learnpython › replace elements in numpy array
r/learnpython on Reddit: Replace elements in numpy array
September 9, 2021 -

I have a function that converts angular values (degrees) into cardinal directions (N, NNW, ect). Here is what I have so far:

import numpy as np

def to_cardinal(values: np.ndarray):

    CARD_DIR = [
        "N",
        "NNE",
        "NE",
        "ENE",
        "E",
        "ESE",
        "SE",
        "SSE",
        "S",
        "SSW",
        "SW",
        "WSW",
        "W",
        "WNW",
        "NW",
        "NNW",
        "N",
    ]

    # If values over 360, scale down
    angle = np.remainder(vals_array, 360.0)

    # Divide by 22.5 and convert to int
    # On another note, not sure if np.around is necessary?
    index_arr = np.around((angle / 22.5)).astype(np.int16, copy=False)

    return index_arr

I return index_arr here because I'm not sure how to continue. Here is a sample input/output:

input = np.array((10, 350, 190, 100, 270, 30))
output = to_cardinal(input)
print(output)

>>> (0, 16, 8, 4, 12, 1)

These values are the indices of the CARD_DIR list that the degree values corresponds to. In words, I need to construct an array (or replace from index_arr) where each element is now the string from CARD_DIR instead of the integer that represents the index. I can imagine doing this in a loop, but how could this be vectorized?

In psuedo-code:

new_array = np.empty(size = index_arr.size)

for i, value in enumerate(index_arr):
    new_array[i] = CARD_DIR[value]

Also, not sure if np.around is necessary when casting a float to an int? Does the int type conversion round correctly already?

Edit: Figured it out, numpy is magical. See comment below! Still interested in type-casting from floats to ints, though.

🌐
Medium
medium.com › @keycomputereducation › numpy-replace-items-that-satisfy-a-condition-300a487ef6a4
Numpy — replace items that satisfy a condition | by Key computer Education | Medium
May 4, 2023 - import numpy as np arr1 = np.array([30,23,67,12,8,9,4]) result1 = np.where( (arr1 > 20) & (arr1 < 30), 0, arr1) # replace with zero print(result1) ... import numpy as np arr1 = np.array([30,23,67,12,8,9,4]) result1 = an_array = np.asarray([0 if val < 30 else 1 for val in the_array]) print(result1)
🌐
IncludeHelp
includehelp.com › python › fast-replacement-of-values-in-a-numpy-array.aspx
Python - Fast replacement of values in a NumPy array
February 7, 2023 - # Import numpy import numpy as np # Creating a numpy array arr = np.array([0,1,6,5,1,2,7,6,2,3,8,7,3,4,9,8,5,6,11,10]) # Display original array print("Original array:\n",arr,"\n") # Creating a dictionary d = {4: 0, 3: 5, 1: 10, 9: 15, 2: 0} # Creating a copy of array new = np.copy(arr) # Replacing values for i,j in d.items(): new[arr==i] = j # Display result print("Result:\n",new)
🌐
GeeksforGeeks
geeksforgeeks.org › replace-numpy-array-elements-that-doesnt-satisfy-the-given-condition
Replace NumPy array elements that doesn’t satisfy the given condition | GeeksforGeeks
October 25, 2020 - This can be achieved using the np.isnan() function along with the Bitwise NOT operator. Note that this approach specifically targets NaN values and may not handle othe ... Given numpy array, the task is to replace negative value with zero in ...
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.char.replace.html
numpy.char.replace — NumPy v2.6.dev0 Manual
>>> a = np.array(["The dish is fresh", "This is it"]) >>> np.strings.replace(a, 'is', 'was') array(['The dwash was fresh', 'Thwas was it'], dtype='<U19') Go BackOpen In Tab ·
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.put.html
numpy.put — NumPy v2.1 Manual
Replaces specified elements of an array with given values. The indexing works on the flattened target array.