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.
We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes. where, inplace parameter accepts True or False, which specifies that change in index is permanent or temporary. True indicates that change is Permanent.
Well, I suppose what you need is
a[a==2] = 10 #replace all 2's with 10's
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With