Skip to main content
 首页 » 编程设计

python之返回未被 Python 中的索引数组引用的元素

2025年05月04日11wayfarer

假设我有一个 Python 数组,例如:

my_array = np.array([10, -5, 4, ...]) 
my_indices = np.array([0, 3, 10, ...]) 

我怎样才能有效地得到:

  1. 不在 my_indices 中的 my_array 的 indices 列表
  2. my_array 中的 elements 列表未被 my_indices referenced(1 微不足道,但也许有直接的方式)

请您参考如下方法:

我可能会这样做:

>>> import numpy as np 
>>> a = np.random.random(10)  # set up a random array to play with 
>>> a 
array([ 0.20291643,  0.89973074,  0.14291639,  0.53535553,  0.21801353, 
        0.05582776,  0.64301145,  0.56081956,  0.85771335,  0.6032354 ]) 
>>> 
>>> b = np.array([0,5,6,9])  # indices we *don't want* 
>>> mask = np.ones(a.shape,dtype=bool) 
>>> mask[b] = False          # Converted to a mask array of indices we *do want* 
>>> mask 
array([False,  True,  True,  True,  True, False, False,  True,  True, False], dtype=bool) 
>>> 
>>> np.arange(a.shape[0])[mask]  #This gets you the indices that aren't in your original 
array([1, 2, 3, 4, 7, 8]) 
>>> a[mask]  #This gets you the elements not in your original. 
array([ 0.89973074,  0.14291639,  0.53535553,  0.21801353,  0.56081956, 
        0.85771335])