I have a 'mask' (boolean) 2D array and I would like to transform it into a list of coordinates. What's the proper numpythonic way to do that ?
The input would be something like this:
[[False,False,True],
[False,True,False]]
and given the above input, the output should be:
[(0,2),(1,1)]
Use
np.where
: Can be used if you want to index another array later with it. But the result is not quite what you specified.np.argwhere
: If you want your specified result. But this result cannot be used for indexing another array.Some example code:
import numpy as np
a = np.array([[False,False,True],
[False,True,False]])
np.argwhere(a) # equivalent to checking a == True
#array([[0, 2],
# [1, 1]], dtype=int64)
np.where(a) # equivalent to checking a == True
#(array([0, 1], dtype=int64), array([2, 1], dtype=int64))
And if you want to convert your result to a list there is a ndarray.tolist()
method. So you can call np.argwhere(a).tolist()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With