在python()中查找作为set array成员的数组元素

2024-04-26 10:42:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

现在在python中:(使用numpy库) 我有一个形状为(1000,15,15)的数组。 我有另一个形状为(500,15,15)的ndarry B。你知道吗

我试图在A中找到B中也是成员的元素。 我特别寻找一个向量,它返回的是a中元素的索引,而B中元素的索引也是。你知道吗

通常在MATLAB中,我将它们重塑为二维数组(1000*225)和(500*225),并使用'ismember'函数,传递'rows'参数来查找并返回相似行的索引。你知道吗

numpy(或任何其他库)中是否有类似的函数来执行相同的操作? 我想避免循环。你知道吗

谢谢


Tags: 函数numpy元素定义成员矩阵数组向量
1条回答
网友
1楼 · 发布于 2024-04-26 10:42:00

这里有一种使用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))

样本运行-

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

相关问题 更多 >