21

I have a NumPy array, A. I want to know the indexes of the elements in A equal to a value and which indexes satisfy some condition:

import numpy as np
A = np.array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])

value = 2
ind = np.array([0, 1, 5, 10])  # Index belongs to ind

Here is what I did:

B = np.where(A==value)[0]  # Gives the indexes in A for which value = 2
print(B)

[1 5 9]

mask = np.in1d(B, ind)  # Gives the index values that belong to the ind array
print(mask)
array([ True, True, False], dtype=bool)

print B[mask]  # Is the solution
[1 5]

The solution works, but I find it complicated. Also, in1d does a sort which is slow. Is there a better way of achieving this?

5 Answers 5

22

If you flip the operation order around you can do it in one line:

B = ind[A[ind]==value]
print B
[1 5]

Breaking that down:

#subselect first
print A[ind]
[1 2 2 3]

#create a mask for the indices
print A[ind]==value
[False  True  True False]

print ind
[ 0  1  5 10]

print ind[A[ind]==value]
[1 5]
Sign up to request clarification or add additional context in comments.

Comments

14
B = np.where(A==value)[0]  #gives the indexes in A for which value = 2
print np.intersect1d(B, ind)
[1 5]

Comments

2

The second two steps can be replaced by intersect1D. Probably also does a sort. Don't know how you'd avoid that unless you can guarantee your ind array is ordered.

Comments

2

How about deferring the np.where until the end, like so:

res = (A == value)
mask = np.zeros(A.size)
mask[ind] = 1
print np.where(res * z)[0]

That shouldn't require any sorting.

Comments

1

This is a bit different - I didn't do any timing tests.

>>> 
>>> A = np.array([1,2,3,4,1,2,3,4,1,2,3,4])
>>> ind = np.array([0,1,5,10])
>>> b = np.ix_(A==2)
>>> np.intersect1d(ind, *b)
array([1, 5])
>>> 

Although after looking at @Robb's solution, that's probably the way to do it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.