Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array filtering twice and replace

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.

like image 415
user3099854 Avatar asked Aug 15 '26 04:08

user3099854


1 Answers

m = b < 6 
b[m] = np.where(b[m]< a,b[m],a)
like image 90
M4rtini Avatar answered Aug 17 '26 17:08

M4rtini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!