【问题标题】:How to search for a particular 2x2 matrix in a 5x2x2 NumPy array?如何在 5x2x2 NumPy 数组中搜索特定的 2x2 矩阵?
【发布时间】:2020-06-16 21:35:15
【问题描述】:

我有一个维度为 (5,2,2) 的 NumPy 数组,它是一系列 2×2 矩阵。我如何询问这些 2×2 矩阵之一是否具有特定值?

比如下面这个系列

import numpy as np
zeros = np.zeros(4).reshape(2,2)
serie = np.array([zeros+1, zeros+2, zeros+3, zeros+4, zeros+5])

然后,serie 中有一个用 2 填充的 2×2 矩阵。如何询问serie 是否包含一个用 2 填充的 2×2 矩阵并检索其索引?在这种情况下,索引将为 1,因为 serie[1,:] 是寻找的矩阵。

【问题讨论】:

    标签: python numpy matrix search indexing


    【解决方案1】:

    使用简单的数组比较,np.allnp.where

    import numpy as np
    
    zeros = np.zeros(4).reshape(2,2)
    serie = np.array([zeros+1, zeros+2, zeros+3, zeros+4, zeros+5])
    
    to_find = zeros+2
    
    index = np.where(np.all(serie == to_find, axis=(1, 2)))[0]
    print(index)
    

    输出:

    [1]
    

    希望有帮助!

    ----------------------------------------
    System information
    ----------------------------------------
    Platform:    Windows-10-10.0.16299-SP0
    Python:      3.8.1
    NumPy:       1.18.1
    ----------------------------------------
    

    【讨论】:

      猜你喜欢
      • 2015-05-12
      • 1970-01-01
      • 2020-02-27
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多