Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
numpy.where() could be useful here, possibly nested... –  MattDMo Dec 13 '13 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 ? –  user3099854 Dec 13 '13 at 15:26

1 Answer 1

up vote 1 down vote accepted
m = b < 6 
b[m] = np.where(b[m]< a,b[m],a)
share|improve this answer
1  
this produces wrong result, its length is equal to len(a). –  alko Dec 13 '13 at 15:39
    
ahh thanks. A little typo. –  M4rtini Dec 13 '13 at 15:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.