Examples of how to find indices of a value in a numpy array (or matrix) in python:
Table of contents
Find indices of a value using "where"
Let's create a 1d matrix with numpy (for that we generate random integers between [0,10[ for a matrix of dimensions (8,))
import numpy as np
a = np.random.randint(10, size=(8,))
print(a)
returns for example
[7 3 5 9 8 0 5 3]
To find the indice of the value 7 for example, a solution is to use numpy where:
np.where(a==7)
returns here:
(array([0]),)
meaning that 7 is at the index 0.
Note that np.where() returns a tuple object:
type(np.where(a==7))
gives
tuple
Another example
np.where(a==8)
returns
(array([4]),)
meaning that 8 is at the index 4.
If a value is present several times, for example with 3, then numpy where
np.where(a==3)
returns several indices
(array([1, 7]),)
Here 3 is at the indices 1 and 7.
Note: code to plot the above figure
a = np.array([7, 3, 5, 9, 8, 0, 5, 3])
a = a[:,np.newaxis]
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
ax = sns.heatmap(a.T, annot=True, fmt="d", cbar=False)
plt.title("How to find indices of a given value \n in a numpy array (or matrix) in python ?",fontsize=12)
plt.savefig("find_indices_value_numpy_matrix_01.png", bbox_inches='tight', dpi=100)
plt.show()
Another example with a 2d matrix
a = np.random.randint(100, size=(8,6))
print(a)
returns
[[31 15 26 54 44 24]
[ 2 54 17 22 54 50]
[ 7 96 50 15 53 81]
[95 3 76 47 27 70]
[ 2 33 72 56 35 8]
[19 47 41 38 38 20]
[72 20 21 34 2 70]
[26 3 52 27 84 72]]
Then for 7
np.where(a==7)
we found
(array([2]), array([0]))
meaning 7 is at the index x0 = 2 and x1 = 0.
Note that for a 2d matrix numpy.where() returns a 2d typle.
Another example
np.where(a==70)
returns
(array([3, 6]), array([5, 5]))
meaning that the value 70 is at the indices (3,5) and (6,5).
References
- numpy.where | scipy doc
- Numpy where function multiple conditions | stackoverflow
- How to use numpy.where with logical operators | stackoverflow
- Is there a Numpy function to return the first index of something in an array? | stackoverflow