在两个2D numpy数组中获取相交的行 [英] Get intersecting rows across two 2D numpy arrays

查看:87
本文介绍了在两个2D numpy数组中获取相交的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get the intersecting (common) rows across two 2D numpy arrays. E.g., if the following arrays are passed as inputs:

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

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

输出应为:

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

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

I know how to do this with loops. I'm looking at a Pythonic/Numpy way to do this.

推荐答案

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

For short arrays, using sets is probably the clearest and most readable way to do it.

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

Another way is to use numpy.intersect1d. You'll have to trick it into treating the rows as a single value, though... This makes things a bit less readable...

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)

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

For large arrays, this should be considerably faster than using sets.

这篇关于在两个2D numpy数组中获取相交的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆