Get (column, row) index from NumPy array that meets a boolean condition

arrays, numpy, python

Solution

Use `numpy.where` with `numpy.column_stack`:

>>> np.column_stack(np.where(b))
array([[1, 2],
       [2, 0],
       [2, 1],
       [2, 2]])

Problem

I am working with a 2D NumPy array. I would like to get the (column, row) index, or (x, y) coordinate, if you prefer thinking that way, from my 2D array that meets a boolean condition. The best way I can explain what I am trying to do is via a trivial example: ``` >>> a = np.arange(9).reshape(3, 3) >>> b = a > 4 >>> b >>> array([[False, False, False], [False, False, True], [ True, True, True]], dtype=bool) ``` At this point I now have a boolean array, indicating where `a > 4`. My goal at this point is grab the indexes of the boolean array where the value is `True`. For example, the indexes `(1, 2)`, `(2, 0)`, `(2, 1)`, and `(2, 2)` all have a value of True. My end goal is to end up with a list of indexes: ``` >>> indexes = [(1, 2), (2, 0), (2, 1), (2, 2)] ``` Again, I stress the point that the code above is a trivial example, but the application of what I'm trying to do could have arbitrary indexes where `a > 4` and not something based on `arange` and `reshape`.

Original source