#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ENGG1811. numpy Boolean indexing - exercise """ import numpy as np # %% Problem parameters # # Create a two dimensional numpy array temp_array = np.array( [[ 0.4, 0.4, 0.6, 0.5, 0.7, 0.8, 0.8, 0.5, 0.0, 0.7], [ 0.4, 0.4, 0.8, 0.4, 0.8, 1.1, 0.9, 0.4, 1.1, 1.1], [ 0.4, 1.1, 0.8, 0.3, 0.7, 1.1, 0.9, 0.5, 1.1, 0.6], [ 0.4, 0.5, 0.6, 0.4, 0.9, 1.2, 0.8, 0.5, 0.1, 0.6], [ 0.3, 0.4, 0.8, 0.3, 0.8, 0.7, 0.7, 0.4, 0.2, 0.7]] ) # Each row contains readings from a sensor # Each column contains the readings from five sensors at a given time # %% # You want to compute the mean of each column after excluding the values >= 1 # # The final answer you want is: # [0.38, 0.425, 0.72, 0.38, 0.78, 0.75, 0.82, 0.46, 0.1, 0.65 ] # Hint: remember mean = sum of readings / number of readings # You on want to use the valid readings in the calculations # Step 1: Sum all the valid readings in a column # # The expected answer is: # [ 1.9, 1.7, 3.6, 1.9, 3.9, 1.5, 4.1, 2.3, 0.3, 2.6] # Step 2: Count the number valid readings # # The expected answer is: # [5, 4, 5, 5, 5, 2, 5, 5, 3, 4] # Step 3: # Compute the mean # Method 1 # Create an array of the same size as temp_array and fill it with 1's mask = np.ones_like(temp_array, dtype = 'int') # Set the elements in the mask to zero if the corresponding element # in temp_array is >= 1 mask[temp_array >= 1] = 0 # Sum the valid readings sum_valid_readings = np.sum(temp_array * mask, axis = 0) # Number of valid readings num_valid_readings = np.sum(mask > 0, axis = 0) # Mean of valid readings mean_valid_readings = sum_valid_readings / num_valid_readings # %% # Method 2: # Make a copy of temp_array temp_array_copy = np.copy(temp_array) # Set invalid readings to zero in temp_array_copy temp_array_copy[temp_array >= 1] = 0 # Sum the valid reading sum_valid_readings_alt = np.sum(temp_array_copy, axis = 0) # Count the number of valid readings num_valid_readings_alt = np.sum(temp_array < 1, axis = 0) # Mean of valid readings mean_valid_readings_alt = sum_valid_readings_alt / num_valid_readings_alt # %% # Note: This won't work: # np.sum(temp_array[temp_array < 1],axis = 0)