Question

I need some help to detect all values (coordinates) of 2D array which verify a specific conditional.

I have already asked a similar question, but now I masked specific values which don't interest me... Last time, a person suggested to use zip(*np.where(test2D < 5000.))

For example:

import numpy as np

test2D = np.array([[  3051.11,   2984.85,   3059.17],
       [  3510.78,   3442.43,   3520.7 ],
       [  4045.91,   3975.03,   4058.15],
       [  4646.37,   4575.01,   4662.29],
       [  5322.75,   5249.33,   5342.1 ],
       [  6102.73,   6025.72,   6127.86],
       [  6985.96,   6906.81,   7018.22],
       [  7979.81,   7901.04,   8021.  ],
       [  9107.18,   9021.98,   9156.44],
       [ 10364.26,  10277.02,  10423.1 ],
       [ 11776.65,  11682.76,  11843.18]])

So I can get all positions which verify < 5000 :

positions=zip(*np.where(test2D < 5000.))

Now I want to reject some values which are useless for me (it s an array with coordinates):

rejectedvalues = np.array([[0, 0], [2, 2], [3, 1], [10, 2]])
i, j = rejectedvalues.T

mask = np.zeros(test2D.shape, bool)
mask[i,j] = True
m = np.ma.array(test2D, mask=mask)

positions2=zip(*np.where(m < 5000.))

But positions2 gives me the same as positions...

Was it helpful?

Solution

np.ma.where respects the mask -- it does not return indices in the condition (e.g. m < 5000.) that are masked.

In [58]: np.asarray(np.column_stack(np.ma.where(m < 5000.)))
Out[58]: 
array([[0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2],
       [2, 0],
       [2, 1],
       [3, 0],
       [3, 2]])

Compare that with the analogous expression using np.where:

In [57]: np.asarray(np.column_stack(np.where(m < 5000.)))
Out[57]: 
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2],
       [2, 0],
       [2, 1],
       [2, 2],
       [3, 0],
       [3, 1],
       [3, 2]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top