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.
I found another solution with the numpy function
place
. (Documentation here)Using it on your example:
Instead of replacing the values one by one, it is possible to remap the entire array like this:
yields
Credit for the above idea goes to @JoshAdel. It is significantly faster than my original answer:
I benchmarked the two versions this way:
Read-only array in numpy can be made writable:
This will then allow assignment operations like this one:
The real problem was not assignment itself but the writable flag.
You can also use
np.choose(idx, vals)
, whereidx
is an array of indices that indicate which value ofvals
should be put in their place. The indices must be 0-based, though. Also make sure thatidx
has an integer datatype. So you would only need to do:Well, I suppose what you need is