grammarly deal
grammarly deal

Reputation: 31

List all x,y of coordinates having specific value in 2D array numpy

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

Upvotes: 2

Views: 3249

Answers (1)

Aguy
Aguy

Reputation: 8059

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.

Upvotes: 5

Related Questions