Find array elements that are members of an array set in python ()

I am new to python and my question may seem very poorly explained because I have experience in MATLAB. usually in MATLAB, if we have 1000 arrays of 15 * 15, we define a cell or 3D matrix, each element of which is a (15 * 15) matrix.

Now in python: (using numpy library) I have an ndarray A with the form (1000,15,15). I have another ndarry B with the shape (500,15,15).

I am trying to find elements in A that are also members of B. I am specifically looking for a vector that will be returned with the indices of elements from A that are also in B.

Usually in MATLAB I modify them to create 2D arrays (1000 * 225) and (500 * 225) and use the "ismember" function passing the "rows" argument to find and return the index of similar rows.

Are there any similar functions in numpy (or any other library) to do the same? I am trying to use aviod for a loop.

thank

+3


source to share


1 answer


Here is one approach using views

heavily based on this post

-

# Based on /questions/2405621/numpy-intersect1d-with-array-with-matrix-as-elements/6250883#6250883 by @Eric
def get_index_matching_elems(a, b):
    # check that casting to void will create equal size elements
    assert a.shape[1:] == b.shape[1:]
    assert a.dtype == b.dtype

    # compute dtypes
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))

    # convert to 1d void arrays
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    a_void = a.reshape(a.shape[0], -1).view(void_dt)
    b_void = b.reshape(b.shape[0], -1).view(void_dt)

    # Get indices in a that are also in b
    return np.flatnonzero(np.in1d(a_void, b_void))

      



Example run -

In [87]: # Generate a random array, a
    ...: a = np.random.randint(11,99,(8,3,4))
    ...: 
    ...: # Generate random array, b and set few of them same as in a
    ...: b = np.random.randint(11,99,(6,3,4))
    ...: b[[0,2,4]] = a[[3,6,1]]
    ...: 

In [88]: get_index_matching_elems(a,b)
Out[88]: array([1, 3, 6])

      

+1


source







All Articles