2

I want to find a "more numpy" than loop&if solution for the task of list all (x,y) of coordinates having value equal to given m in 2D array python.

e.g: this is a 4x4 matrix

0 1 1 0
0 2 2 0
0 2 1 0
0 0 0 0

and if m = 2, I want the list of [(1,1), (1,2), (2,1)] since those cells = 2. what I want is their coordinates.

and if m = 1 then [(0,1), (0,2), (2,2)] due to cells = 1.

I don't want solution of looping and if and put i,j into the list. It's a bit slow, any solution using numpy for faster ? Thanks

Some suggest me to take a look at this numpy get index where value is true but I tried and it doesn't correct.

To be detail:

np.where(np.any(e==1, axis=0) in the case give out: [1,2] Yes! agree

np.where(np.any(e==1, axis=1) give out: [0,2] Yes! still ok BUT it doesn't lead to this: [(0,1), (0,2), (2,2)] because row or column info is not enough,

So please don't underestimate this question and delete my question again and again. I'm tired of it

  • Your linked question does recommend `argwhere` or `transpose(where())`, same as your accepted answer. – hpaulj Aug 03 '20 at 03:54
  • 1
    Does this answer your question? [numpy get index where value is true](https://stackoverflow.com/questions/16094563/numpy-get-index-where-value-is-true) – AMC Aug 03 '20 at 04:49

1 Answers1

5

Lose the np.any part. Like this:

np.array(np.where(e==1)).T

The external np.array and the transpose .T are just to arrange the indices in a way that will be easy for you to read.

Aguy
  • 7,851
  • 5
  • 31
  • 58