The objective is to extract the coordinate where a cell equal to 1 in a 2D array
[[1. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0.]]
Here the coordinate is flip than the conventional
8
7
6
5
4
3
2
1
0
0 1 2 3 4 5 6 7 8
Hence, for the 2D array above,
the output where cell equal to 1 is
[(0, 8),(2,4),(3,8)]
I curious how can I tweak the np.where by taking consideration this type of coordinate.
Simply
cor=np.array(np.where(arr==1)).T
as expected will give different result than I expect.
The above array can be reproduce
arr=np.zeros((9,9))
arr[0,0]=1
arr[4,2]=1
arr[0,3]=1
Remark, the order is not important, such that
[(0, 8),(2,4),(3,8)] is equivalent to [(8, 0),(4,2),(8,3)]
>Solution :
The function np.where for a 2D array returns Tuple(np.ndarray, np.ndarray)where the first entry of the tuple contains all row indices and the second one all column indices. So if you want to index the tranposed array you have to swap the tuple entries:
indices = np.where(condition)[::-1]
If you want to transform the coordinate format to the list of 2-element-tuple you could do:
indices = [(n_rr, c) for r, c in zip(np.where(condition))]
Edit:
After clarification, I now understand that rpb wants to change the origin of indexing, so that the zeroth row becomes the last and so on. Furthermore, the coordinates are desired in the format of 2element tuple per found entry.
import numpy as np
arr=np.zeros((9,9))
arr[0,0]=1
arr[4,2]=1
arr[0,3]=1
print(arr)
print(np.where(arr==1.)[0])
n_rows = arr.shape[0]
indices = [(n_rows - 1 -r, c) for r, c in zip(*np.where(arr==1.))]
print(indices)
>>> [(8, 0), (8, 3), (4, 2)]