Introduction to NumPy and Matplotlib
Chapter 3: Array operations
Boolean indexing
You can also access elements using a boolean np.array as its indices.
This is where boolean expressions (x < 3) become useful! These can be used to filter your np.array. Possibly one of the most useful features that you may end up using a lot!
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
In Line 10, note the & instead of our usual and in pure Python. This is actually a bitwise and operator (and works for boolean expressions). The and operator is not overloaded for np.array.
Unfortunately you cannot chain 1 < y < 4 either.
Also note the parenthesis surrounding the two expressions (y < 4) and (y > 1). The operator & has higher precedence, so without the parenthesis, it will be interpreted as y < (4 & y) < 1, resulting in an error.
More advanced indexing techniques are covered in the official documentation.