3

I want to execute two filtering and one replacing steps on a large array but I cannot figure a way to do it efficiently without making some copy or for loop.

Example, imagine two numpy arrays of different sizes. I want to apply two filters. The first one to select only elements of b that are inferior to 6 (b') and a second filters to replace the values of b' by the values of a if a is inferior to b':

a = np.array( [ 2,2,2,2,2,2] )
b = np.array( [ 0,1,2,3,4,5,6,7,8,9] )

I apply a first masking by selecting the elements of b inferior to 6 :

m = b < 6 

Now, I want to replace the value of b[m] by the minimal value between a and b[m], with expected results in b :

[ 0,1,2,2,2,2,6,7,8,9]

Using :

n = a < b[m]
b[m][n] = a[n]

doesn't work. Probably because of some intermediate array. With

c = np.array( [ 0, 1, 2, 3, 4, 5  ] )

I can directly do :

c[ a < c ] = a [ a < c ]

and it works. Any cool slicing way to do it without making secondary array ? Thanks.

2
  • numpy.where() could be useful here, possibly nested... Commented Dec 13, 2013 at 15:19
  • I just found a way : b [ b[b < 6] > a ] = a [ b[ b < 6 ] > a ] but it's not really elegant. Any better idea ? Commented Dec 13, 2013 at 15:26

1 Answer 1

1
m = b < 6 
b[m] = np.where(b[m]< a,b[m],a)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.