i would like to return the index of a given value in a (30,3) numpy array. The array looks like this:
[[x11,x12,x13]
[x21,x22,x23]
[x31,x32,x33]
[...]
[...]]
My goal is to extract the index of the row of a given value [x21,x22,x23].
Any hints are grealy appreciated!
CodePudding user response:
import numpy as np
arr = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
row_num = np.shape(arr)[1]
target_row = np.array([7,8,9])
for i in range(row_num):
if np.array_equal(arr[i], target_row):
target_row_index = i
break
By looping through each row in the numpy array you can check if it is the one that matches the desired row. This index can then be stored or returned.
CodePudding user response:
Provided a random 30 by 3 matrix arr
and a random array row
of size 3 like so,
import numpy as np
from random import randint
arr = np.random.rand(30, 3)
row = arr[randint(0, len(arr))]
You can figure out the indices of all matching rows with the following expression. If you are certain there is only one matching row, you can get the first item.
np.arange(len(arr))[(arr == row).all(axis=1)]