Get complement of numpy array
Question:
I have the following array and a list of indices
my_array = np.array([ [1,2], [3,4], [5,6], [7,8] ])
indices = np.array([0,2])
I can get the values of the array corresponding to my indices by just doing my_array[indices]
, which gives me the expected result
array([[1, 2],
[5, 6]])
Now I want to get the complement of it. As mentioned in one of the answers, doing
my_array[~indices]
Will not give the expected result [[3,4],[7,8]]
.
I was hoping this could be done in a 1-liner way, without having to define additional masks.
Answers:
You can use numpy.delete
. It returns a new array with sub-arrays along an axis deleted.
complement = np.delete(my_array, indices, axis=0)
>>> np.delete(my_array, indices, axis=0)
array([[3, 4],
[7, 8]])
I have the following array and a list of indices
my_array = np.array([ [1,2], [3,4], [5,6], [7,8] ])
indices = np.array([0,2])
I can get the values of the array corresponding to my indices by just doing my_array[indices]
, which gives me the expected result
array([[1, 2],
[5, 6]])
Now I want to get the complement of it. As mentioned in one of the answers, doing
my_array[~indices]
Will not give the expected result [[3,4],[7,8]]
.
I was hoping this could be done in a 1-liner way, without having to define additional masks.
You can use numpy.delete
. It returns a new array with sub-arrays along an axis deleted.
complement = np.delete(my_array, indices, axis=0)
>>> np.delete(my_array, indices, axis=0)
array([[3, 4],
[7, 8]])