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

同一条目的多个实例的numpy.searchsorted-python

  •  0
  • SuperCiocia  · 技术社区  · 7 年前

    将numpy作为np导入

    gens = np.array([2, 1, 2, 1, 0, 1, 2, 1, 2])
    p = [0,1]
    

    gens 匹配 p .

    result = [[4],[2,3,5,7],[0,2,6,8]] 
    #[[where matched 0], [where matched 1], [the rest]]
    

    --

    indx = gens.argsort()
    res = np.searchsorted(gens[indx], [0])
    gens[res] #gives 4, which is the position of 0
    

    但我试着

    indx = gens.argsort()
    res = np.searchsorted(gens[indx], [1])
    gens[res] #gives 1, which is the position of the first 1.
    

    所以:

    • 如何搜索出现多次的条目
    • 倍数
    1 回复  |  直到 7 年前
        1
  •  0
  •   Andreas K.    7 年前

    你可以用 np.where

    >>> np.where(gens == p[0])[0]
    array([4])
    
    >>> np.where(gens == p[1])[0]
    array([1, 3, 5, 7])
    
    >>> np.where((gens != p[0]) & (gens != p[1]))[0]
    array([0, 2, 6, 8])
    

    或者 np.in1d np.nonzero

    >>> np.nonzero(np.in1d(gens, p[0]))[0]
    
    >>> np.nonzero(np.in1d(gens, p[1]))[0]
    
    >>> np.nonzero(~np.in1d(gens, p))[0]