Python NumPy - Numerical Operations on Arrays

Premium

Arrays have a unique advantage over Python lists in that they allow you to perform element-wise operations without the need for a for loop. This makes computations very efficient specially while dealing with large data sets.

Suppose we have a list and we want to multiply all its elements by 3 (scalar). If we try to directly multiply it by three, it will just add the list elements three times, which is not what we wanted.

1>>> a = [1,3,5]
2>>> a*3
3[1, 3, 5, 1, 3, 5, 1, 3, 5]
4>>>
5

To get the right results, you will use the for-loop approach which would look as follows:

1>>> a = [1,3,5]
2>>> b = [3*x for x in a]
3>>> b
4[3, 9, 15]
5>>>
6

Grouping these element-wise operations together, a process known as vectorization, allows NumPy to perform such computations much more rapidly as shown below:

1>>> import numpy as np
2>>> a = np.array([1, 3, 5])
3>>> b = a*3
4>>> b
5array([ 3,  9, 15])
6>>>
7

These vectorized operations are not just restricted to interactions between arrays and scalars. We can even perform fast element-wise operations between arrays. The following example shows element-wise subtraction of two arrays.

1>>> a = np.array([10,15,18])
2>>> b = np.array([4,5,6])
3>>> c = a - b
4>>> c
5array([ 6, 10, 12])
6>>>
7

When the shapes of the two arguments are not the same, but share a common shape dimension, the operation is broadcasted across the array. In other words, NumPy expands the arrays such that the operation becomes viable. This process is called broadcasting.

1>>> b
2array([4, 5, 6])
3>>> x= np.arange(6).reshape((2,3))
4>>> x
5array([[0, 1, 2],
6       [3, 4, 5]])
7>>> y=x*b
8>>> y
9array([[ 0,  5, 12],
10       [12, 20, 30]])
11>>>
12

There are broadcasting rules but we will discuss those in an advanced course on NumPy.

Exercises

  • Using NumPy array, create a vector with values ranging from 10 to 49
  • Create a 3x3 matrix with values ranging from 0 to 8. Multiply all the elements of the matrix with a magnitude of 3.