2

Suppose that you have a 1D numpy array containing elements that are either 3 or 4

for example:

3
4
4
4
3
3
3

I would like to alter this array so that if an element is 3 then it should become some number X and if the element is 4 it should become some number Y. It is guaranteed that X is different than Y. For the above array we would get:

X
Y
Y
Y
X
X
X

I was thinking about doing something like this:

arr[arr==3]=X
arr[arr==4]=Y

however, what if X is 4? Then in the end the entire array will contain just Ys.

I am trying to avoid using a for loop for performance reasons, but if it's the only way to go, I can afford following that route.

Divakar
  • 218,885
  • 19
  • 262
  • 358
ksm001
  • 3,772
  • 10
  • 36
  • 57
  • 3
    `arr==3` will just give you a boolean array. You can first get the output of `arr==3` and `arr==4` before setting the new values. – cel Sep 14 '15 at 10:44

2 Answers2

6

Since the input 1D array contains only 3 or 4, you can use np.where, like so -

np.where(A==3,X,Y)

Sample run #1 -

In [55]: A
Out[55]: array([4, 3, 4, 3, 3, 3, 4, 4, 4, 4, 3, 3, 4, 3, 4])

In [56]: X = 30; Y = 40

In [57]: np.where(A==3,X,Y)
Out[57]: array([40, 30, 40, 30, 30, 30, 40, 40, 40, 40, 30, 30, 40, 30, 40])

Sample run #2 (if X is 4) -

In [60]: A
Out[60]: array([4, 3, 4, 3, 3, 3, 4, 4, 4, 4, 3, 3, 4, 3, 4])

In [61]: X = 4; Y = 40

In [62]: np.where(A==3,X,Y)
Out[62]: array([40,  4, 40,  4,  4,  4, 40, 40, 40, 40,  4,  4, 40,  4, 40])
Divakar
  • 218,885
  • 19
  • 262
  • 358
1

This is a typical use for the map function. A way of implementing it would be:

result = map(lambda k: X if k==3 else Y, myarray)

You can replace k == 3 with any function that returns a boolean like so:

result = map(lambda k: X if myfun(k) else Y, myarray)

You may want to consider this post, however you will not get much speed up.

Community
  • 1
  • 1
rll
  • 5,509
  • 3
  • 31
  • 46