在python中找到属于set数组成员的数组元素 [英] find array elements that are members of set array in python ()

查看:281
本文介绍了在python中找到属于set数组成员的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我的问题似乎很难解释,因为我在MATLAB中有背景. 通常在MATLAB中,如果我们有1000个15 * 15的数组,我们定义一个单元格或3D矩阵,每个元素都是一个大小为(15 * 15)的矩阵.

I am new to python and my question might seem very badly explained because I have background in MATLAB. usually in MATLAB if we have 1000 arrays of 15*15 we define a cell or a 3D matrix which each element is a matrix with size (15*15).

现在在python中:(使用numpy库) 我有一个形状为(1000,15,15)的ndarrayA. 我还有另一个形状(500,15,15)的ndarry B.

Now in python: (using numpy library) I have a ndarray A with shape (1000,15,15). I have another ndarry B with shape (500,15,15).

我也试图在A中查找属于B的元素. 我专门在寻找一个向量,该向量也将与在B中找到的A中元素的索引一起返回.

I am trying to find elements in A that are member in B too. I am specifically looking for a vector to be returned with the indices of elements in A that are found in B too.

通常在MATLAB中,我将它们整形为2D数组(1000 * 225)和(500 * 225),并使用'ismember'函数,传递'rows'参数以查找并返回相似行的索引.

Usually in MATLAB I reshape them to make 2D arrays (1000*225) and (500*225) and use 'ismember' function, passing 'rows' argument to find and return the index of the similar rows.

在numpy(或任何其他库)中是否有任何类似的功能可以执行相同的操作? 我试图避免循环.

Are there any similar functions in numpy (or any other library) to do the same? I am trying to aviod for loop.

谢谢

推荐答案

这是使用views的一种方法,主要基于 this post -

Here'e one approach using views largely based on this post -

# Based on https://stackoverflow.com/a/41417343/3293881 by @Eric
def get_index_matching_elems(a, b):
    # check that casting to void will create equal size elements
    assert a.shape[1:] == b.shape[1:]
    assert a.dtype == b.dtype

    # compute dtypes
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))

    # convert to 1d void arrays
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    a_void = a.reshape(a.shape[0], -1).view(void_dt)
    b_void = b.reshape(b.shape[0], -1).view(void_dt)

    # Get indices in a that are also in b
    return np.flatnonzero(np.in1d(a_void, b_void))

样品运行-

In [87]: # Generate a random array, a
    ...: a = np.random.randint(11,99,(8,3,4))
    ...: 
    ...: # Generate random array, b and set few of them same as in a
    ...: b = np.random.randint(11,99,(6,3,4))
    ...: b[[0,2,4]] = a[[3,6,1]]
    ...: 

In [88]: get_index_matching_elems(a,b)
Out[88]: array([1, 3, 6])

这篇关于在python中找到属于set数组成员的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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