Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 914
abudis Avatar asked Nov 26 '12 20:11

abudis


People also ask

Can you convert a NumPy array to a list?

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.

How do you replace an index in a list?

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.

How do you change the index value in Python?

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.


1 Answers

Well, I suppose what you need is

a[a==2] = 10 #replace all 2's with 10's 
like image 192
alex_jordan Avatar answered Sep 20 '22 19:09

alex_jordan