Boolean indexing in Python using Numpy
It is the advanced indexing technique which makes you to select the elements of an array. It uses a Boolean mask (has two values True/False).
Let us create this in 3 different ways as follows.
- Boolean indexing in 1D array
- Boolean indexing in 2D array
- Boolean indexing using Multiple conditions.
Each one is explained with sample code as below.
👉Boolean indexing in 1D array
This
program reads a single dimensional array as input. It uses a single condition
to find Boolean mask. It finds the value and displays the result.
Code:
import numpy as np1
s_arr = np1.array([11, 22, 33, 40, 55 ,66, 75])
mask = s_arr > 33
print("The resultant values are:\n",mask)
result = s_arr[mask]
print("The result which satisfies the condition
s_arr>33:\n",result)
🖵Output:
The resultant values are:
[False False
False True True
True True]
The result which satisfies the condition s_arr>33:
[40 55 66 75]
Boolean indexing with 2D arrays:
This program uses 2D array as input. It checks each and
every value, whether it meets the condition. Based on that, it displays the
output.
Code:
import numpy as np1
s_arr = np1.array([[1, 2, 3],
[4, 5,
6],
[7, 8,
9]])
mask = s_arr > 4
print("The resultant values are:\n",mask)
result = s_arr[mask]
print("The result which satisfies the condition
s_arr>5:\n",result)
🖵Output:
The resultant values are:
[[False False False]
[False True
True]
[ True True
True]]
The result which satisfies the condition s_arr>5:
[5 6 7 8 9]
Boolean indexing with multiple conditions:
This
program uses multiple conditions for mask.
Code:
import numpy as np1
s_arr = np1.array([[1, 2, 3],
[4, 5,
6],
[7, 8,
9]])
mask = (s_arr > 4) & (s_arr <8)
print("The resultant values are:\n",mask)
result = s_arr[mask]
print("The result which satisfies the multiple
conditions:\n",result)
🖵Output:
The resultant values are:
[[False False False]
[False True
True]
[ True False False]]
The result which satisfies the multiple conditions:
[5 6 7]
These are the different ways to find Boolean indexing in python
using Numpy. Hope, this code is useful to you. Keep Coding!!!
Comments
Post a Comment