test for membership in a 2d numpy array

前端 未结 4 758
花落未央
花落未央 2020-12-03 08:05

I have two 2D arrays of the same size

a = array([[1,2],[3,4],[5,6]])
b = array([[1,2],[3,4],[7,8]])

I want to know the rows of b that are i

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 09:01

    If you have smth like a=np.array([[1,2],[3,4],[5,6]]) and b=np.array([[5,6],[1,2],[7,6]]), you can convert them into complex 1-D array:

    c=a[:,0]+a[:,1]*1j
    d=b[:,0]+b[:,1]*1j
    

    This whole stuff in my Interpreter looks like this:

    >>> c=a[:,0]+a[:,1]*1j
    >>> c
    array([ 1.+2.j,  3.+4.j,  5.+6.j])
    >>> d=b[:,0]+b[:,1]*1j
    >>> d
    array([ 5.+6.j,  1.+2.j,  7.+6.j])
    

    And now that you have just 1D array, you can easily do np.in1d(c,d), and the Python will give you:

    >>> np.in1d(c,d)
    array([ True, False,  True], dtype=bool)
    

    And with this you don't need any loops, at least with this data type

提交回复
热议问题