1

I have a numpy 2D array of some dimension say 2 by 2 (in numpy.float32 dtype)

[[0.001 0.02],
 [0.3 0.9]]

I want to create a new mask matrix for the given matrix such that,

if a1<= matrix element <a2:
    new element = a3
if b1<= matrix element <b2:
    new element = b3
... Can have up to 10 conditions like this

For example if the conditions are:

if 0.0<= matrix element <0.05:
    new element = 10
if 0.05<= matrix element <1.0:
    new element = 5

The given matrix should transforms to:

[[10.0 10.0],
 [5.0 5.0]]

Can someone please help me to obtain the mask matrix for any given matrix with given set of conditions?

Usecase Basically instead of just using np.sum(numpy 2D array), I want to do a weighted sum of matrix elements. So the conditions are actually defining the weights.

Once having the original matrix and the mask matrix I shall then do element-wise multiplication of both matrices and then use np.sum on the resulting 2D array.

Probably would like to have less for loops as possible for fast execution. I am using Python 3.7.

This post is similar but do not really understand if that solves my task.

Thankyou

1 Answer 1

3

You can achieve this result with numpy.select and a dictionary summarizing your conditions.

arr = np.array([[0.001, 0.02], [0.3, 0.9]])
selection_dict = {10: (0<=arr)&(arr<0.05),
                  5:  (0.05<=arr)&(arr<1.0)}

In [52]: np.select(condlist=selection_dict.values(), choicelist=selection_dict.keys())
Out[52]: 
array([[10, 10],
       [ 5,  5]])
Sign up to request clarification or add additional context in comments.

5 Comments

That dictionary is a bit redundant, no? :-)
I am not sure what you mean by "redundant"
You're creating a dict, just to take it apart again in the next line.
Oh right ! I prefer to use a dict rather than two lists, because it keeps the conditions on the same line as the values. With two lists, if you have something like 20 conditions you might shift one by mistake
Could you please accept the answer if this helped you, thanks !

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.