python - 在 python () 中查找作为集合数组成员的数组元素

标签 python arrays numpy find

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

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

我正在尝试在 A 中查找也是 B 中的成员的元素。 我正在专门寻找一个向量来返回,其中包含在 B 中也找到的 A 中的元素索引。

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

在 numpy(或任何其他库)中是否有类似的函数来做同样的事情? 我试图避免 for 循环。

谢谢

最佳答案

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

# 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))

sample 运行-

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 - 在 python () 中查找作为集合数组成员的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43480797/

相关文章:

python - 推送被拒绝,无法在heroku中编译Python应用程序(Python速成类(class))

python - 嵌入 matplotlib 图形并更改其大小

python - 解释elasticsearch的minimum_should_match

c - C 中 char 数组的 if 语句

python - 在 Python 中读取 scipy/numpy 中的 csv 文件

Python - Pandas,重新采样数据集以具有平衡的类

python - OpenSSL 加密错误 : [ ('PEM routines' , 'PEM_read_bio' , 'no start line' )]

c - 在一个数组中,如何检查其任意两个内容数字之和是否可以等于某个值 x?

arrays - 作业 C 用字符串编程栈和堆

python - 广播从矩阵创建的子张量(Theano)