【问题标题】:find array elements that are members of set array in python ()在python()中查找作为set数组成员的数组元素
【发布时间】:2017-09-14 19:14:33
【问题描述】:

我是 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 中,我将它们重塑为 2D 数组 (1000*225) 和 (500*225) 并使用 'ismember' 函数,传递 'rows' 参数来查找并返回相似行的索引。

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

谢谢

【问题讨论】:

标签: python arrays numpy find


【解决方案1】:

这是使用views 的一种方法,主要基于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])

【讨论】:

    猜你喜欢
    • 2014-04-06
    • 2017-04-11
    • 2011-05-12
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    相关资源
    最近更新 更多