如何检查Numpy数组是否是另一个更大数组的子数组 [英] How to check if a Numpy array is a subarray of another bigger array

查看:97
本文介绍了如何检查Numpy数组是否是另一个更大数组的子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有两个数组,我想检查一个数组是否在另一个数组中...我正在寻找一种方法来做这样的事情:

So basically I have two arrays, and I want to check if one array is in another... I'm looking for a way to do something like this:

>>> arr1 = np.array([1, 0, 0, 1, 1, 0])
>>> arr2 = np.array([0, 0, 1, 1, 1, 0])
>>> test_array = np.array([1, 1, 1])
>>> test_array in arr1
... False
>>> test_array in arr2
... True

有没有办法解决类似这样的问题?谢谢。

Is there any way to solve do something like this? Thanks.

推荐答案

尝试使用2D蒙版:

ix = np.arange(len(arr1) - len(test_array))[:,None] + np.arange(len(test_array))
(arr1[ix] - test_array).all(axis=1).any()
>> False
(arr2[ix] - test_array).all(axis=1).any()
>> True

或在函数中:

def array_in(arr, test_arr):
    return (arr[np.arange(len(arr) - len(test_arr))[:,None] +
               np.arange(len(test_arr))] == test_arr).all(axis=1).any()

这篇关于如何检查Numpy数组是否是另一个更大数组的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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