how to get a numpy ndarray without the elements satisfying specified conditions

Viewed 25
# 1. generate a numpy array called 'np2' with (3, 4) shape, as below;
np2 = np.arange(11, 23).reshape(3, 4)
# [[11 12 13 14]
#  [15 16 17 18]
#  [19 20 21 22]]

# 2. with given conditions '(np2 < 18) & (np2 % 2 == 0))', get the index of elements in np2 satisfying the condition;
print(np.where((np2 < 18) & (np2 % 2 == 0)))
# (array([0, 0, 1]), array([1, 3, 1]))

# 3. get the elements in np2 which satisfy the condition. in this case, [12 14 16]
print(np2[np.where((np2 < 18) & (np2 % 2 == 0))])
# [12 14 16]

# 4. check the index of [12] in np2, it is a tuple '(array([0]), array([1]))'.
print(np.where(np2==12))
# (array([0]), array([1]))

# 5. delete the elements in np2 satisfying condition: I did not expect to see [12], [14] and [16] appearing in np2_idx, but they did.
np2_idx = np.delete(np2, np.where((np2 < 18) & (np2 % 2 == 0)))
print(np2_idx)
# [13 14 15 16 17 18 19 20 21 22]

can anyone help to explain how I finallly got '[13 14 15 16 17 18 19 20 21 22]' rather than '[11 13 15 17 18 19 20 21 22]'?

if there's no way to work with 'np.delete' and 'np.where', any smarter way to achieve my purpose?

1 Answers

A smarter way, in my opinion, would just be to inverse your boolean mask:

m = (np2 < 18) & (np2 % 2 == 0)
np2_idx = np2[~m]

output: array([11, 13, 15, 17, 18, 19, 20, 21, 22])

Related