Replace values of a numpy index array with values of a list

numpy replace values in 2d array
numpy 2d array replace values by index
numpy where
replace value in numpy array by index
numpy replace multiple values in array
numpy replace values condition
set values of a numpy array
numpy put 2d array

Suppose you have a numpy array and a list:

>>> a = np.array([1,2,2,1]).reshape(2,2)
>>> a
array([[1, 2],
       [2, 1]])
>>> b = [0, 10]

I'd like to replace values in an array, so that 1 is replaced by 0, and 2 by 10.

I found a similar problem here - http://mail.python.org/pipermail//tutor/2011-September/085392.html

But using this solution:

for x in np.nditer(a):
    if x==1:
        x[...]=x=0
    elif x==2:
        x[...]=x=10

Throws me an error:

ValueError: assignment destination is read-only

I guess that's because I can't really write into a numpy array.

P.S. The actual size of the numpy array is 514 by 504 and of the list is 8.

Instead of replacing the values one by one, it is possible to remap the entire array like this:

import numpy as np
a = np.array([1,2,2,1]).reshape(2,2)
# palette must be given in sorted order
palette = [1, 2]
# key gives the new values you wish palette to be mapped to.
key = np.array([0, 10])
index = np.digitize(a.ravel(), palette, right=True)
print(key[index].reshape(a.shape))

yields

[[ 0 10]
 [10  0]]

Credit for the above idea goes to @JoshAdel. It is significantly faster than my original answer:

import numpy as np
import random
palette = np.arange(8)
key = palette**2
a = np.array([random.choice(palette) for i in range(514*504)]).reshape(514,504)

def using_unique():
    palette, index = np.unique(a, return_inverse=True)
    return key[index].reshape(a.shape)

def using_digitize():
    index = np.digitize(a.ravel(), palette, right=True)
    return key[index].reshape(a.shape)

if __name__ == '__main__':
    assert np.allclose(using_unique(), using_digitize())

I benchmarked the two versions this way:

In [107]: %timeit using_unique()
10 loops, best of 3: 35.6 ms per loop
In [112]: %timeit using_digitize()
100 loops, best of 3: 5.14 ms per loop

numpy.put — NumPy v1.19 Manual, Replaces specified elements of an array with given values. The indexing works on the flattened target array. put is roughly equivalent to: a.flat[ind] = v. Values of this array range between 0 and 10 what coincides with the indices of a 1D numpy array (length of 1D array = 11, so 0-10) . This 1D array stores abritrary values. I want now to replace the indices values of my 2D array with the corresponding values from the 1D array.

Well, I suppose what you need is

a[a==2] = 10 #replace all 2's with 10's

numpy - Replace values in an array - Python code example, Python code example 'Replace values in an array' for the package numpy, powered by Kite. for this numpy 1.8 added the at reduction: at(a, indices, b=None) Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'. For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once.

Read-only array in numpy can be made writable:

nArray.flags.writeable = True

This will then allow assignment operations like this one:

nArray[nArray == 10] = 9999 # replace all 10's with 9999's

The real problem was not assignment itself but the writable flag.

NumPy: Replace all elements of numpy array that are greater than , NumPy Array Object Exercises, Practice and Solution: Write a Write a NumPy program to replace all elements of NumPy array that are greater than specified array. Let's try to modify the list that was passed to a method:. I have a numpy master array. Given another array of search values, with repeating elements, I want to produce the indices of these search values in the master array. E.g.: master array is [1,2,3,4,5], search array is [4,2,2,3] Solution: [3,1,1,2] Is there a "native" numpy function that does this efficiently (meaning at C speed, rather than

I found another solution with the numpy function place. (Documentation here)

Using it on your example:

>>> a = np.array([1,2,2,1]).reshape(2,2)
>>> a
array([[1, 2],
   [2, 1]])
>>> np.place(a, a==1, 0)
>>> np.place(a, a==2, 10)
>>> a
array([[ 0, 10],
       [10,  0]])

numpy.where(): Process elements depending on conditions, Using numpy.where(), elements of the NumPy array ndarray that satisfy the conditions Overview of np.where() Multiple conditions Replace the elements that satisfy the con. np.where() is a function that returns ndarray which is x if condition is True and y if False If x and y are omitted, index is returned. Replace all elements of Python NumPy Array that are greater than some value: stackoverflow: Replace “zero-columns” with values from a numpy array: stackoverflow: numpy.place: numpy doc: Numpy where function multiple conditions: stackoverflow: Replace NaN's in NumPy array with closest non-NaN value: stackoverflow: numpy.put: numpy doc: numpy.nan_to_num: numpy doc

You can also use np.choose(idx, vals), where idx is an array of indices that indicate which value of vals should be put in their place. The indices must be 0-based, though. Also make sure that idx has an integer datatype. So you would only need to do:

np.choose(a.astype(np.int32) - 1, b)

Python, Python: Numpy's Structured Array � How to sort a Numpy Array | Python � Python | Find Mean of a List of Numpy Array � Python | Ways to add row/columns in� print(cord) print("*** Get the index of an element based on multiple conditions Numpy Array ***") # Create a numpy array from a list of numbers. arr = np.array( [11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17]) # Get the index of elements with value less than 16 and greater than 12.

How to Replace Values by Index in a Tensor with TensorFlow-2.0, How a seemingly straightforward operation in NumPy turns into a Have you ever tried to replace only certain values of array, based on their indices? I accomplished this by using the function tf.gather( a, idx_keep ) which� Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem. Method #1: Naive Method.

Fancy Indexing, In this section, we'll look at another style of array indexing, known as fancy indexing. Alternatively, we can pass a single list or array of indices to obtain the same result: Here, each row value is matched with each column vector, exactly as we saw in indices = np.random.choice(X.shape[0], 20, replace=False) indices. # app.py import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 19, 13, 14, 15, 11, 19, 21, 19, 20, 21]) result = np.where(arr == 19) print('Tuple of arrays returned : ', result) print("Elements with value 19 exists at following indices", result[0], sep=' ')

How to replace some elements of a matrix using numpy in python ?, Using multiple conditions; Using the numpy function where; References. Replace some elements of a 1D matrix. Let's try to replace the elements� NumPy: Array Object Exercise-88 with Solution. Write a NumPy program to replace all elements of NumPy array that are greater than specified array.

Comments
  • Thanks unutbu! I'll accept your answer as it's more versatile. Cheers.
  • "index = np.digitize(a.reshape(-1,), palette)-1" could be replaced with "index = np.digitize(a.reshape(-1,), palette, right=True)", right? (=True?)
  • @PietroBattiston: Since every value in a is in palette, yes I think right=True returns the same result. Thanks for the improvement!
  • What would we do, if we wanted to change values at indexes which are multiple of given n, like a[2],a[4],a[6],a[8]..... for n=2?
  • When I do this, I get "assignment destination is read-only", do you know why this is?
  • This is significantly simpler than the other solutions, thank you
  • What would we do, if we want to change the elements at indexes which are multiple of given n, simultaneously. Like simultaneously change a[2],a[4],a[6].... for n = 2., what should be done?