
How to select the subarray of a NumPy array satisfying a condition
The following code shows to get the subarray of an array satisfying the condition.
import numpy
a = numpy.array([3, 5, 7, 9, 11])
b = a[a > 6]
print(b) # [ 7 9 11]
The sentence in brackets is the condition. You can select the even integers as array.
import numpy
a = numpy.array([1, 2, 3, 4])
b = a[a % 2 == 0]
print(b) # [2 4]
Matrix and condition
Here's an example of selecting items from matrix.
import numpy
a = numpy.array([[1, 2, 3], [4, 5, 6]])
b = a[a > 2]
print(b) # [3 4 5 6]
Comments
Powered by Markdown