Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace elements in numpy array using list of old and new values

I want to replace elements in a numpy array using a list of old values and new values. See below for a code example (replace_old is the requested method). The method must work for both int, float and string elements. How do I do that?

import numpy as np

dat = np.hstack((np.arange(1,9), np.arange(1,4)))
print dat # [1 2 3 4 5 6 7 8 1 2 3]

old_val = [2, 5]
new_val = [11, 57]

new_dat = replace_old(dat, old_val, new_val)
print new_dat # [1 11 3 4 57 6 7 8 1 11 3]
like image 465
pir Avatar asked Jul 09 '15 12:07

pir


People also ask

What does .values do in NumPy?

values returns a numpy array with the underlying data of the DataFrame, without any index or columns names.


1 Answers

You can use np.place :

>>> np.place(dat,np.in1d(dat,old_val),new_val)
>>> dat
array([ 1, 11,  3,  4, 57,  6,  7,  8,  1, 11,  3])

For creating the mask array you can use np.in1d(arr1,arr2) which will give you :

a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise

Edit:Note that the preceding recipe will replace old_values based on those order and as @ajcr mentioned it wont work for another arrays,so as a general way for now I suggest the following way using a loop (which I don't think that was the best way):

>>> dat2 = np.array([1, 2, 1, 2])
>>> old_val = [1, 2]
>>> new_val = [33, 66]

>>> z=np.array((old_val,new_val)).T
>>> for i,j in z:
...    np.place(dat2,dat2==i,j)
... 
>>> dat2
array([33, 66, 33, 66])

In this case you create a new array (z) which is contains the relevant pairs from old_val and new_val and then you can pass them to np.place and replace them .

like image 143
Mazdak Avatar answered Oct 23 '22 03:10

Mazdak