[Numpy-discussion] finding index in an array...

Emmanuelle Gouillart emmanuelle.gouillart at normalesup.org
Sat Jun 13 05:04:11 EDT 2009

Hi Fred,

here is another solution
>>> A = np.arange(99).reshape((33,3)
>>> mask = (A==np.array([0,1,2]))
>>> np.nonzero(np.prod(mask, axis=1))[0]

I found it to be less elegant than Josef's solution changing the dtype of
the array, but it may be easier to understand if you're not very familiar
with dtypes. Also, it is a bit faster on my computer:
>>> %timeit np.nonzero(A.view([('',int)]*3) == np.array((0,1,2),[('',int)]*3))[0]
10000 loops, best of 3: 61.8 µs per loop
>>> %timeit np.nonzero(np.prod((A==np.array([0,1,2])), axis=1))[0]
10000 loops, best of 3: 38.1 µs per loop



On Sat, Jun 13, 2009 at 01:08:48AM +0200, fred wrote:
> Hi,

> Say I have an array A with shape (10,3) and

> A[3,:] = [1,2,3]

> I want to find the index of the array in which I have these values [1,2,3].

> How can I do that?

> The only workaround I have found is to use a list:

> A.tolist().index([1,2, 3])

> That works fine, but is there a better solution (without using list, for
> instance)?

> TIA.

> Cheers,

More information about the NumPy-Discussion mailing list