Filtering arrays with Boolean indexing
You can also index arrays using Boolean indexing. By creating a Boolean array where the values are True
for the indices you want to retain, you can filter an array. This can be especially convenient for filtering one array based upon the values in another array.
In this exercise, you'll explore how birth weight varies between animals that tend to have one baby per birth versus those that have multiple. Two NumPy arrays are loaded into your workspace, along with the NumPy package as np
.
litter_size
is the average size of a litter for each of 1200+ animalsbirth_weight
is the corresponding average birth weight in grams for each animal
This exercise is part of the course
Python for MATLAB Users
Exercise instructions
- Create Boolean arrays
mono_births
andmulti_births
for animals that typically have a single offspring per litter and those that have greater than one, respectively. - Create arrays
mono_birth_weight
andmulti_birth_weight
, which contain the birth weights of single offspring animals and multi-offspring animals, respectively. - Print the mean birth weight of animals which tend to have a single offspring per litter and those that have greater than one.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create Boolean arrays that indicate mono births and multi births
mono_births = litter_size ____ 1.0
multi_births = ____
# Create two arrays of birth weights for mono and multi births
mono_birth_weight = birth_weight[____]
multi_birth_weight = ____
# Calculate the mean birth weight for mono birth and multi birth animals
print(np.____(mono_birth_weight))
print(np.____(____))