Say I have two Numpy
arrays:
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([7, 8, 9])
How do I easily find where b
exists in a
? In this case I want 2
. numpy.where()
returns useful information but it still has to be processed. I have written a function for that, as can be seen below, but there must be an easier way.
def find_vertical_array_index(a, b):
"""Find array in another array.
Parameters
----------
a: numpy array
Array to find array in.
b: numpy array
Array to find array. Must have dimensions 1 by n.
Returns
-------
Integer value of index where b first occurs in a.
Notes
-----
Only searches through the array vertically and returns the first index.
If array does not occur, nothing is returned.
Examples
--------
>>> x = np.array([[5, 3, 1, 1], [9, 9, 9, 8], [9, 3, 7, 9]])
>>> y = np.array([9, 9, 9, 8])
>>> find_vertical_array_index(x, y)
1
>>> x = np.array([[9, 9, 9, 8], [9, 9, 9, 8], [9, 3, 7, 9]])
>>> y = np.array([9, 9, 9, 9])
0
"""
try:
index = list(Counter(np.where(a == b)[0]).values()).index(len(b))
except ValueError:
pass
return list(Counter(np.where(a == b)[0]).keys())[index]