假设我在Python中有一个数组,例如:
my_array = np.array([10, -5, 4, ...])
my_indices = np.array([0, 3, 10, ...])
Run Code Online (Sandbox Code Playgroud)
我怎样才能有效地获得:
my_array不在my_indicesmy_array不提及的my_indices(琐碎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])
Run Code Online (Sandbox Code Playgroud)