Extract elements from numpy array, that are not in list of indexes

前端 未结 4 2187
梦谈多话
梦谈多话 2020-12-06 19:38

I want to do something similar to what was asked here NumPy array, change the values that are NOT in a list of indices, but not quite the same.

Consider a nump

相关标签:
4条回答
  • 2020-12-06 19:43

    One approach with np.in1d to create the mask of the ones from indxs present and then inverting it and indexing the input array with it for the desired output -

    a[~np.in1d(np.arange(a.size),indxs)]
    
    0 讨论(0)
  • 2020-12-06 19:45
    In [170]: a = np.array([0.2, 5.6, 88, 12, 1.3, 6, 8.9])
    In [171]: idx=[1,2,5]
    In [172]: a[idx]
    Out[172]: array([  5.6,  88. ,   6. ])
    In [173]: np.delete(a,idx)
    Out[173]: array([  0.2,  12. ,   1.3,   8.9])
    

    delete is more general than you really need, using different strategies depending on the inputs. I think in this case it uses the boolean mask approach (timings should be similar).

    In [175]: mask=np.ones_like(a, bool)
    In [176]: mask
    Out[176]: array([ True,  True,  True,  True,  True,  True,  True], dtype=bool)
    In [177]: mask[idx]=False
    In [178]: mask
    Out[178]: array([ True, False, False,  True,  True, False,  True], dtype=bool)
    In [179]: a[mask]
    Out[179]: array([  0.2,  12. ,   1.3,   8.9])
    
    0 讨论(0)
  • 2020-12-06 19:56

    One way is to use a boolean mask and just invert the indices to be false:

    mask = np.ones(a.size, dtype=bool)
    mask[indxs] = False
    a[mask]
    
    0 讨论(0)
  • 2020-12-06 19:58

    You could use the enumerate function, excluding the indexes:

    [x for i, x in enumerate(a) if i not in [1, 2, 5] ]
    

    including them:

    [x for i, x in enumerate(a) if i in [1, 2, 5]]
    
    0 讨论(0)
提交回复
热议问题