Boolean Indexing¶
In [1]:
%pip install numpy
import numpy as np
Requirement already satisfied: numpy in /home/samrat/Documents/numpy-torch-tutorials/venv/lib/python3.8/site-packages (1.24.4) Note: you may need to restart the kernel to use updated packages.
In [2]:
foo = np.array([
[3, 9, 7],
[2, 0, 3],
[3, 3, 1]
])
In [4]:
mask = foo == 3
mask
Out[4]:
array([[ True, False, False], [False, False, True], [ True, True, False]])
In [5]:
foo[mask] = 0
foo
Out[5]:
array([[0, 9, 7], [2, 0, 0], [0, 0, 1]])
In [6]:
rows_1_and_3 = np.array([True, False, True]) # (0, 1)
cols_2_and_3 = np.array([False, True, True]) # (1, 2)
In [7]:
foo[rows_1_and_3]
Out[7]:
array([[0, 9, 7], [0, 0, 1]])
In [8]:
foo[:, cols_2_and_3]
Out[8]:
array([[9, 7], [0, 0], [0, 1]])
In [9]:
foo[rows_1_and_3, cols_2_and_3]
Out[9]:
array([9, 1])
In [10]:
names = np.array(["Dennis", "Dee", "Charlie", "Mac", "Frank"])
ages = np.array([43,44, 43,42,74])
genders = np.array(['male', 'female', 'male','male', 'male'])
In [12]:
# At least 44 years old
age_mask = ages >= 44
names[age_mask]
Out[12]:
array(['Dee', 'Frank'], dtype='<U7')
In [21]:
# Males over 42
males_42_mask = (genders == 'male') & (ages > 42)
names[males_42_mask]
Out[21]:
array(['Dennis', 'Charlie', 'Frank'], dtype='<U7')
In [24]:
# Not a male or younger than 43
not_male_43_mask = ~(genders == 'male') | (ages < 43)
names[not_male_43_mask]
Out[24]:
array(['Dee', 'Mac'], dtype='<U7')