1

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]
H. Vabri
  • 314
  • 1
  • 2
  • 13
  • 1
    With `b` as `2D`, you could use : [`Find the row indexes of several values in a numpy array`](http://stackoverflow.com/questions/38674027/find-the-row-indexes-of-several-values-in-a-numpy-array). – Divakar Dec 01 '16 at 09:58
  • Is there a reason you use numpy arrays instead of simple Python lists (which have the index method you are looking for) ? – Daneel Dec 01 '16 at 10:03
  • Could there be duplicate rows in `a`? That line : `"Integer value of index where b first occurs in a."` made me think about it. – Divakar Dec 01 '16 at 10:04
  • @Daneel: arrays are used because the arrays are used in other numpy operations. @Divakar: duplicate rows are allowed, but the function returns the index where it first found `b`. – H. Vabri Dec 01 '16 at 16:47

0 Answers0