This is an archived version of the course. Please see the latest version of the course.

NumPy exercises

Now that you have spent so much time reading, it is time to get your hands dirty with NumPy!

Many thanks to the following people for contributing to these exercises: Joe Stacey

Task 1

Multiply each element of np.arange(10) by 2

Task 2

Try doing the following using NumPy:

  • Create an identity matrix
  • Find the square root of each element in an array
  • Square each element in an array
  • Take logs of each element in an array
  • Create an array of zeros
  • Create an array of ones
  • Give the value of \(\pi\)
  • Transpose an array
  • Round down a float
  • Find the median of floats in a NumPy array
  • Add a new element to a NumPy array

Task 3

Create a \(1 \times 40\) 1D array, and then convert this into a \(8 \times 5\) 2D NumPy array.

Task 4

Create a \(1 \times 2000\) NumPy array with the step-wise sequence from 1 to 2000, and then convert this into a \(40 \times 50\) 2D NumPy array.

Then

  • Index this array correctly to return the value 435
  • Index this array correctly to return the value 951

Task 5

What happens when we use .ravel()?

  • For example: How is np.arange(20).reshape(20, 1).ravel() different to np.arange(20).reshape(20, 1)?
  • Try using .shape to help investigate

Task 6

We can use .all() to check whether two NumPy arrays are identical. Which of the following do you expect to return True? Check your answers using Python.

  • (np.arange(20).reshape(20,1) == np.arange(20)).all()
  • (np.arange(20).reshape(20,1).ravel() == np.arange(20)).all()
  • (np.arange(20).reshape(20,1,1).ravel() == np.arange(20)).all()
  • (np.arange(20).reshape(20,) == np.arange(20)).all()
  • (np.arange(20).reshape(20,) == np.arange(20).ravel()).all()

Task 7

Normalise the vector reprsented by np.array([3, 5, 1, 2, 4]) to find the unit vector in the same direction.