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

Mohit Lamba
  • 1,194
  • 13
  • 30

1 Answers1

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]])
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
AMH
  • 502
  • 2
  • 10