I have an array
v = (x,y,z)
and two multidimensional array
l = (a,b,c),(d,e,f)
and
r = (g,h,i),(l,m,n),(x,y,z).
I want to know the index of v no matter if is in the first or second multidimensional array. I tried numpy.where(v==l)[0][0] but it returns:
Index 0 is out of bounds for axis 0 with size 0.
Works only if I know before the matrix where I have to search the Index, but I don't. Thanks
And If I want to know the index and the array that contains it?
解决方案
Define a function that accepts the item to be searched and the list of array to be searched in and use a loop to find that item in each array. Use exception handling to catch the IndexError.
>>> import numpy as np
>>> v = np.array([[1, 2, 3]])
>>> r = np.array([[1, 2, 3], [0, 9, 8], [2, 4, 4]])
>>> l = np.array([[4, 5, 6], [7, 8, 9]])
def get_index(seq, *arrays):
for array in arrays:
try:
return np.where(array==seq)[0][0]
except IndexError:
pass
...
>>> get_index(v, r, l)
0
>>> get_index(np.array([7, 8, 9]), r, l)
1
You'd get None as output if the item is not found in any of the array.
Update:
If you want the name as well then pass the arrays in a dictionary:
def get_index(seq, **arrays):
for name, array in arrays.items():
try:
return name, np.where(array==seq)[0][0]
except IndexError:
pass
...
>>> get_index(v, **dict(r=r, l=l))
('r', 0)
>>> get_index(np.array([7, 8, 9]), **dict(r=r, l=l))
('l', 1)