LoslegenKostenlos loslegen

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+ animals
  • birth_weight is the corresponding average birth weight in grams for each animal

Diese Übung ist Teil des Kurses

Python for MATLAB Users

Kurs anzeigen

Anleitung zur Übung

  • Create Boolean arrays mono_births and multi_births for animals that typically have a single offspring per litter and those that have greater than one, respectively.
  • Create arrays mono_birth_weight and multi_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.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# 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.____(____))
Code bearbeiten und ausführen