Python NumPy - Numerical Operations on Arrays

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.

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

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

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

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

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

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.

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

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.

Related Downloads