检查两个2D numpy数组的公共元素(按行或按列) [英] Check common elements of two 2D numpy arrays, either row or column wise

查看:96
本文介绍了检查两个2D numpy数组的公共元素(按行或按列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个分别为 nx3 mx3 numpy 数组,这是一种确定行索引(计数器)的有效方法,其中行是在两个数组中相同.例如,我有以下解决方案,即使没有更大的数组,它的速度也很慢

Given two numpy arrays of nx3 and mx3, what is an efficient way to determine the row indices (counter) wherein the rows are common in the two arrays. For instance I have the following solution, which is significantly slow for not even much larger arrays

def arrangment(arr1,arr2):
    hits = []
    for i in range(arr2.shape[0]):
        current_row = np.repeat(arr2[i,:][None,:],arr1.shape[0],axis=0)
        x = current_row - arr1
        for j in range(arr1.shape[0]):
            if np.isclose(x[j,0],0.0) and np.isclose(x[j,1],0.0) and np.isclose(x[j,2],0.0):
                hits.append(j)

    return hits

它检查 arr1 中是否存在 arr2 的行,并返回与行匹配的 arr1 的行索引.我需要这种安排始终按照 arr2 的行顺序升序.例如给出

It checks if rows of arr2 exist in arr1 and returns the row indices of arr1 where the rows match. I need this arrangement to be always sequentially ascending in terms of rows of arr2. For instance given

arr1 = np.array([[-1., -1., -1.],
       [ 1., -1., -1.],
       [ 1.,  1., -1.],
       [-1.,  1., -1.],
       [-1., -1.,  1.],
       [ 1., -1.,  1.],
       [ 1.,  1.,  1.],
       [-1.,  1.,  1.]])
arr2 = np.array([[-1.,  1., -1.],
       [ 1.,  1., -1.],
       [ 1.,  1.,  1.],
       [-1.,  1.,  1.]])

该函数应返回:

[3, 2, 6, 7]

推荐答案

快速而肮脏的答案

(arr1[:, None] == arr2).all(-1).argmax(0)

array([3, 2, 6, 7])


更好的答案
照顾机会 arr2 中的行与 arr1

t = (arr1[:, None] == arr2).all(-1)
np.where(t.any(0), t.argmax(0), np.nan)

array([ 3.,  2.,  6.,  7.])


@Divakar指出的 np.isclose 解释了比较浮点数时的舍入误差


As pointed out by @Divakar np.isclose accounts for rounding error in comparing floats

t = np.isclose(arr1[:, None], arr2).all(-1)
np.where(t.any(0), t.argmax(0), np.nan)

这篇关于检查两个2D numpy数组的公共元素(按行或按列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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