NumPy ExercisesΒΆ
Now that weβve learned about NumPy letβs test your knowledge. Weβll start off with a few simple tasks, and then youβll be asked some more complicated questions.
Import NumPy as npΒΆ
import numpy as np
Create an array of 10 zerosΒΆ
np.zeros(10)
Create an array of 10 onesΒΆ
arr = np.ones(10)
arr
Create an array of 10 fivesΒΆ
arr * 5
Create an array of the integers from 10 to 50ΒΆ
SOLUTIONS includes 50 like this:
np.arange(10,51)
np.arange(10,50)
Create an array of all the even integers from 10 to 50ΒΆ
SOLUTIONS includes 50 like this:
np.arange(10,51,2)
same here - 51 to be used so 50 is included - noted for others like this as well
np.arange(10,50,2)
Create a 3x3 matrix with values ranging from 0 to 8ΒΆ
np.arange(0,9).reshape(3,3)
Create a 3x3 identity matrixΒΆ
np.eye(3)
Use NumPy to generate a random number between 0 and 1ΒΆ
np.random.rand(1)
Use NumPy to generate an array of 25 random numbers sampled from a standard normal distributionΒΆ
np.random.randn(25)
Create the following matrix:ΒΆ
SOLUTIONS a little different but same result
np.linspace(0.01,1,100).reshape(10,10)
Create an array of 20 linearly spaced points between 0 and 1:ΒΆ
np.linspace(0,1,20)
Numpy Indexing and SelectionΒΆ
Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs:
mat = np.arange(1,26).reshape(5,5)
mat
mat[2:,1:]
mat[3,4]
SOLUTIONS includes 3rd element to return them like below:
mat[:3,1:2]
mat[:3,1]
mat[4]
mat[3:]
Now do the followingΒΆ
Get the sum of all the values in matΒΆ
np.sum(mat)
Get the standard deviation of the values in matΒΆ
np.std(mat)
Get the sum of all the columns in matΒΆ
np.sum(mat, axis=0)