代码之家  ›  专栏  ›  技术社区  ›  jxramos

为什么numpy。所有假布尔的列表的argmax是否为零?

  •  6
  • jxramos  · 技术社区  · 8 年前

    我正在使用 numpy.argmax True 可以在布尔向量中找到。调用 pandas.Series

    我在我的代码中发现了一个微妙的错误,当向量都是假的时候,它就出现了;在这种情况下返回索引0似乎很危险,因为True很可能是True位于第一个元素中的情况。这个返回值的设计选择是什么?

    >>> numpy.argmax([False,False,False])
    0
    >>> numpy.argmax([True, False, True])
    0
    
    >>> s = pandas.Series( [ False, False, False ] , index=[3,6,9] )
    >>> numpy.argmax(s)
    3
    >>> s1 = pandas.Series( [ True, False, False ] , index=[3,6,9] )
    >>> numpy.argmax(s1)
    3
    
    3 回复  |  直到 8 年前
        1
  •  7
  •   bphi    8 年前

    从源代码:

    In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.

    在向量全部为假的情况下,最大值为零,因此返回最大值第一次出现的索引,即0。

        2
  •  2
  •   jxramos    8 年前

    因此,在一天结束时,这是对 argmax (这是一个简单的函数),忘记了 False True argmax 元素),并期望它像普通 find 函数具有返回空列表的常见约定 [] -1 对于索引,甚至 None 在这种情况下,元素不会退出。

    我最终将最终解决方案编码如下

    s = pandas.Series( listOfBools )
    idx = s.argmax()
    
    if idx == s.index[0] and not s[idx] :
       return -1
    return idx
    
        3
  •  1
  •   jondo    8 年前

    如果您使用的是pandas,您可以用它自己屏蔽布尔级数,然后取该级数的最小值或最大值吗?如果没有真值,则会给出nan。

    >>> s = pd.Series([False, False, True, False, True, False], 
                      index=[0, 1, 2, 3, 4, 5])
    >>> s[s].index.max()
    4
    >>> s[s].index.min()
    2
    >>> s = pd.Series([False, False, False], index=[0,1,2])
    >>> s[s].index.max()
    nan