1

Would like to build a list of indices into a 2 dimensional bool_ array, where True.

import numpy
arr = numpy.zeros((6,6), numpy.bool_)
arr[2,3] = True
arr[5,1] = True
results1 = [[(x,y) for (y,cell) in enumerate(arr[x].flat) if cell] for x in xrange(6)]
results2 = [(x,y) for (y,cell) in enumerate(arr[x].flat) if cell for x in xrange(6)]

results 1:

[[], [], [(2, 3)], [], [], [(5, 1)]]

results 2 is completely wrong

Goal:

[(2, 3),(5, 1)]

Any way to do this without flattening the list afterwards, or any better way to do this in general?

2 Answers 2

1

I think the function you're looking for is numpy.where. Here's an example:

>>> import numpy
>>> arr = numpy.zeros((6,6), numpy.bool_)
>>> arr[2,3] = True
>>> arr[5,1] = True
>>> numpy.where(arr)
(array([2, 5]), array([3, 1]))

You can turn this back into an index like this:

>>> numpy.array(numpy.where(arr)).T
array([[2, 3],
       [5, 1]])
Sign up to request clarification or add additional context in comments.

2 Comments

Oh dear, hadn't heard of that. zip(*numpy.where(arr)) is working nicely. I'll leave this open for awhile to hear if anyone else has alternatives.
np.where() with a single argument is equivalent to np.nonzero(). To transform to the OP's format: np.transpose(np.nonzero(a)) that is equivalent to np.argwhere(a).
0
>>> import numpy as np
>>> arr = np.zeros((6,6), np.bool_)
>>> arr[2,3] = True
>>> arr[5,1] = True
>>> np.argwhere(arr)
array([[2, 3],
       [5, 1]])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.