/logo-square.png

Python NumPy For Your Grandma - 4.8 Challenge: Movie Ratings

Setup You’re given a 10x2 array of floats where each row represents a movie. The first column represents the movie’s rating and the second column represents the director’s rating. Your goal is to create a third column to represent the overall rating. The overall rating is equal to the movie rating if it exists, otherwise it’s the director’s rating. import numpy as np generator = np.random.default_rng(123) ratings = np.round(generator.uniform(low = 0.

Python NumPy For Your Grandma - 4.9 Challenge: Big Fish

Setup 10 fish occupy a 5x5x5 grid of water. Each fish decides to move to a new (i,j,k) location given by the matrix below. If multiple fish end up occupying the same cell, the biggest fish eats the smaller fish. Determine which fish will survive. import numpy as np locs = np.array([ [0,0,0], [1,1,2], [0,0,0], [2,1,3], [5,5,4], [5,0,0], [5,0,0], [0,0,0], [2,1,3], [1,3,1] ]) generator = np.random.default_rng(1010) weights = generator.normal(size=10) print(weights) ## [-1.

Python NumPy For Your Grandma - 5.1 Advanced Array Indexing

Earlier in the course we discussed array indexing techniques, but the truth is I glossed over a lot of gritty details and complex scenarios. In this section, we’ll take a deeper dive into how array indexing works. Let’s start by setting up a 3x2x4 array of integers called foo. import numpy as np foo = np.arange(3*2*4).reshape((3,2,4)) print(foo) ## [[[ 0 1 2 3] ## [ 4 5 6 7]] ## ## [[ 8 9 10 11] ## [12 13 14 15]] ## ## [[16 17 18 19] ## [20 21 22 23]]] What do you think the result of foo[:,:,0] will return?

Python NumPy For Your Grandma - 5.2 View vs Copy

In this section, we’ll shed some light on when array indexing produces a view and when it produces a copy. Say we have this 2d array, squid. import numpy as np squid = np.arange(12).reshape(3,-1) print(squid) ## [[ 0 1 2 3] ## [ 4 5 6 7] ## [ 8 9 10 11]] And we index the array like this, where we use slices to pick out every row and the first two columns.

Python NumPy For Your Grandma - 5.3 Challenge: Population Verification

Setup You manage a local department for the Census responsible for measuring the population of each block in the city where you live. Even though you could do it yourself, for each of the last five years, you’ve tasked this job to your subordinate, Jim. What Jim gives you each year is a 2x4 array of his population estimates where each element of the array represents a city block. After five years, you have a 5x2x4 array of population estimates called jim where (i,j,k) represents Jim’s population estimate for block (j,k) of year i.