Numpy Where () with All() on a 2D matrix

Numpy Where () with All() on a 2D matrix

A= np.random.randint(5, size=(25, 4, 4))
U= np.unique(A, axis =0 )
results = np.where((A==U[0]).all(axis=-1))

使用这个 Where 函数匹配单独的行,我想匹配整个 4x4 数组而不仅仅是单独的行。

以下是示例结果: (数组([ 1, 97, 97, 97, 97], dtype=int64), 数组([0, 0, 1, 2, 3], dtype=int64))

如果所有四行都匹配,结果将包含与上面的索引 97 相同的索引 4 次,单个行与索引“1”匹配。

我假设如果整个数组都匹配,那么只会返回一个索引。 如果为一个数组提供多个索引,则所需输出的示例: (数组([97, 97, 97, 97], dtype=int64), 数组([0, 1, 2, 3], dtype=int64)

np.where((A.reshape(A.shape[0],-1) == U[0].reshape(-1)).all(axis=1))

让我们看一个例子

>>> A = np.random.randint(5, size=(25, 4, 4))
>>> A[:3,...]
array([[[0, 2, 0, 1],
        [1, 0, 3, 0],
        [4, 1, 1, 2],
        [0, 1, 0, 0]],

       [[1, 3, 2, 3],
        [2, 4, 2, 1],
        [3, 3, 2, 3],
        [4, 2, 1, 1]],

       [[4, 0, 3, 3],
        [1, 0, 4, 4],
        [0, 0, 2, 3],
        [4, 1, 2, 2]]])
>>> U = np.unique(A, axis=0)
>>> U[0]
array([[0, 2, 0, 1],
       [1, 0, 3, 0],
       [4, 1, 1, 2],
       [0, 1, 0, 0]])

现在你要在 A 中查找 U[0] 如果我没理解错的话。逐行匹配更容易,所以让我们将 4x4 数组重新整形为行

>>> A.reshape(A.shape[0], -1)[:3,...]
array([[0, 2, 0, 1, 1, 0, 3, 0, 4, 1, 1, 2, 0, 1, 0, 0],
       [1, 3, 2, 3, 2, 4, 2, 1, 3, 3, 2, 3, 4, 2, 1, 1],
       [4, 0, 3, 3, 1, 0, 4, 4, 0, 0, 2, 3, 4, 1, 2, 2]])
>>> U[0].reshape(-1)
array([0, 2, 0, 1, 1, 0, 3, 0, 4, 1, 1, 2, 0, 1, 0, 0])

现在我们可以将它们与 np.where 进行比较,但是如果我们不小心,我们会得到一个元素比较,所以我们需要使用 np.all(axis=1) 来确保逐行比较它们:

>>> np.where(np.all(A.reshape(25, -1) == U[0].reshape(-1), axis=1))
(array([0]),)

编辑 我刚刚想到你可以使用多个轴 np.all 并避免完全重塑:

np.where((A == U[0]).all(axis=(1,2)))