【问题标题】:find function matlab in numpy/scipy在 numpy/scipy 中查找函数 matlab
【发布时间】:2013-01-01 13:33:36
【问题描述】:

对于 numpy/scipy,matlab 中是否有 find(A>9,1) 的等效函数。我知道 numpy 中有 nonzero 函数,但我需要的是第一个索引,以便我可以在另一个提取的列中使用第一个索引。

例如:A = [ 1 2 3 9 6 4 3 10 ] find(A>9,1) 将在 matlab 中返回索引 4

【问题讨论】:

  • 你的意思是>= 吗?因为> 会返回 8。
  • 实际上,numpy 数组是从零开始的,所以9 位于3 位置,10 位于7 位置。

标签: function matlab numpy find scipy


【解决方案1】:

numpy中find的等价物是nonzero,但是不支持第二个参数。 但是你可以做这样的事情来获得你正在寻找的行为。

B = nonzero(A >= 9)[0] 

但是,如果您正在寻找的只是找到满足条件的第一个元素,那么您最好使用max

例如,在 matlab 中,find(A >= 9, 1)[~, idx] = max(A >= 9) 相同。 numpy 中的等效函数如下。

idx = (A >= 9).argmax()

【讨论】:

    【解决方案2】:

    matlab 的find(X, K) 大致相当于python 中的numpy.nonzero(X)[0][:K]。如果K == 1,@Pavan 的 argmax 方法可能是一个不错的选择,但除非您先验地知道 A >= 9 中会有一个值,否则您可能需要执行以下操作:

    idx = (A >= 9).argmax()
    if (idx == 0) and (A[0] < 9):
        # No value in A is >= 9
        ...
    

    【讨论】:

      【解决方案3】:

      我确信这些都是很好的答案,但我无法使用它们。但是,我发现另一个线程部分回答了这个问题: MATLAB-style find() function in Python

      John 发布了以下代码,它解释了 find 的第一个参数,在你的情况下是 A>9 ---find(A>9,1)-- 但不是第二个参数。

      我修改了 John 的代码,我认为这是第二个参数“,1”的原因

      def indices(a, func):
          return [i for (i, val) in enumerate(a) if func(val)]
      a = [1,2,3,9,6,4,3,10]
      threshold = indices(a, lambda y: y >= 9)[0]
      

      这将返回阈值=3。我的理解是Python的索引从0开始......所以它相当于matlab说4。您可以通过更改括号中的数字来更改被调用的索引的值,即[1]、[2]等而不是[0]。

      约翰的原始代码:

      def indices(a, func):
          return [i for (i, val) in enumerate(a) if func(val)]
      
      a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
      
      inds = indices(a, lambda x: x > 2)
      

      返回 >>> inds [2, 5, 8]

      【讨论】:

        【解决方案4】:

        考虑在 Python 中使用 argwhere 来替换 MATLAB 的 find 函数。例如,

        import numpy as np
        A = [1, 2, 3, 9, 6, 4, 3, 10]
        np.argwhere(np.asarray(A)>=9)[0][0] # Return first index
        

        返回 3。

        【讨论】:

          【解决方案5】:
          import numpy
          A = numpy.array([1, 2, 3, 9, 6, 4, 3, 10])
          index = numpy.where(A >= 9)
          

          您可以先将列表转换为 ndarray,然后使用函数 numpy.where() 来获取所需的索引。

          【讨论】:

            猜你喜欢
            • 2013-10-04
            • 2020-10-23
            • 1970-01-01
            • 2016-03-27
            • 2012-11-29
            • 2015-01-26
            • 1970-01-01
            • 2022-06-13
            • 1970-01-01
            相关资源
            最近更新 更多