Question

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

At beginning, i try to convert my 2D array in an 1D one and i get the iteration (position) in the 1D array but that seems to be difficult to find the good position and not very "safe" when i reconvert in 2D...

Is it possible to detect that without 1D transformation? Thanks for help!

As 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]])

a,b = test2D.shape

test1D = np.reshape(test2D,(1,a*b))

positions=[]

for i in range(test1D.shape[1]):
    if test1D[0,i] > 5000.:
        positions.append(i)

print positions

So for this example my input is the 2D array "test2D" and i want all coordinates which verify the condition >5000 as a list.

Was it helpful?

Solution

If you want positions, use something like

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

Numpy.where

This will return

In [15]: zip(*np.where(test2D > 5000.))

Out[15]: 
[(4, 0),
 (4, 1),
 (4, 2),
 (5, 0),
 (5, 1),
 (5, 2),
 (6, 0),
 (6, 1),
 (6, 2),
 (7, 0),
 (7, 1),
 (7, 2),
 (8, 0),
 (8, 1),
 (8, 2),
 (9, 0),
 (9, 1),
 (9, 2),
 (10, 0),
 (10, 1),
 (10, 2)]

OTHER TIPS

In general, when you use numpy.arrays, you can use conditions in fancy indexing. For example, test2D > 5000 will return a boolean array with the same dimensions as test2D and you can use it to find the values where your condition is true: test2D[test2D > 5000]. Nothing else is needed. Instead of using indexes, you can simply use the boolean array to index other arrays than test2D of the same shape. Have a look here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top