user3329302
user3329302

Reputation: 627

Indexes of elements in NumPy array that satisfy conditions on the value and the index

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?

Upvotes: 21

Views: 50313

Answers (5)

wwii
wwii

Reputation: 23743

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.

Upvotes: 1

Robb
Robb

Reputation: 433

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]

Upvotes: 22

Praveen
Praveen

Reputation: 7222

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.

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249093

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

Upvotes: 14

Paul
Paul

Reputation: 43620

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.

Upvotes: 2

Related Questions