在两个2D numpy数组中获取相交的行

发布于 2021-01-29 17:28:01

我想得到两个2D numpy数组的相交(公用)行。例如,如果以下数组作为输入传递:

array([[1, 4],
       [2, 5],
       [3, 6]])

array([[1, 4],
       [3, 6],
       [7, 8]])

输出应为:

array([[1, 4],
       [3, 6])

我知道如何使用循环。我正在寻找一种Pythonic / Numpy方式来做到这一点。

关注者
0
被浏览
193
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    对于短数组,使用集合可能是最清晰,最易读的方法。

    另一种方法是使用numpy.intersect1d。不过,您必须欺骗它,以将行作为单个值来对待……这使事情的可读性降低了……

    import numpy as np
    
    A = np.array([[1,4],[2,5],[3,6]])
    B = np.array([[1,4],[3,6],[7,8]])
    
    nrows, ncols = A.shape
    dtype={'names':['f{}'.format(i) for i in range(ncols)],
           'formats':ncols * [A.dtype]}
    
    C = np.intersect1d(A.view(dtype), B.view(dtype))
    
    # This last bit is optional if you're okay with "C" being a structured array...
    C = C.view(A.dtype).reshape(-1, ncols)
    

    对于大型数组,这应该比使用集合快得多。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看