假设我有两个Numpy
数组:
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([7, 8, 9])
如何轻松找到b
中a
的位置?在这种情况下,我想要2
。 numpy.where()
会返回有用的信息,但仍需要处理。我已经为此编写了一个函数,如下所示,但必须有一个更简单的方法。
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]