Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 201
user3329302 Avatar asked Aug 22 '14 01:08

user3329302


People also ask

What is index in NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How can we use conditions in NumPy within an array?

It returns a new numpy array, after filtering based on a condition, which is a numpy-like array of boolean values. For example, if condition is array([[True, True, False]]) , and our array is a = ndarray([[1, 2, 3]]) , on applying a condition to array ( a[:, condition] ), we will get the array ndarray([[1 2]]) .


2 Answers

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]
like image 112
Robb Avatar answered Oct 14 '22 20:10

Robb


B = np.where(A==value)[0]  #gives the indexes in A for which value = 2
print np.intersect1d(B, ind)
[1 5]
like image 22
John Zwinck Avatar answered Oct 14 '22 19:10

John Zwinck