Arithmetic#

Arrays allow you to perform stack operations on data without having to use for loops. This is called vectorisation in NumPy. For all arithmetic operations between arrays of the same size, the operation is applied element by element:

[1]:
import numpy as np


data = np.random.randn(7, 3)
data
[1]:
array([[-0.52169857, -0.06638825, -1.70235417],
       [ 0.3540172 , -1.30560063, -1.0368024 ],
       [-0.4163764 , -1.24874081, -1.85063163],
       [-0.63982944, -0.47325691,  1.42545299],
       [ 1.11960638,  1.49821503, -0.11843174],
       [-0.59220784,  0.63391355,  1.21890647],
       [-0.57770878,  1.05719525,  2.54019148]])
[2]:
1 / data
[2]:
array([[ -1.91681569, -15.06290747,  -0.58742183],
       [  2.82472155,  -0.765931  ,  -0.96450394],
       [ -2.40167311,  -0.8008067 ,  -0.54035605],
       [ -1.56291653,  -2.11301722,   0.70153138],
       [  0.89317104,   0.66746093,  -8.44368223],
       [ -1.68859637,   1.57750217,   0.82040749],
       [ -1.73097595,   0.94589907,   0.39367111]])
[3]:
data**2
[3]:
array([[2.72169395e-01, 4.40739915e-03, 2.89800972e+00],
       [1.25328175e-01, 1.70459301e+00, 1.07495921e+00],
       [1.73369306e-01, 1.55935360e+00, 3.42483742e+00],
       [4.09381707e-01, 2.23972103e-01, 2.03191622e+00],
       [1.25351846e+00, 2.24464828e+00, 1.40260776e-02],
       [3.50710120e-01, 4.01846387e-01, 1.48573298e+00],
       [3.33747430e-01, 1.11766179e+00, 6.45257275e+00]])

Comparison of two arrays:

[4]:
data2 = np.random.randn(7, 3)
data > data2
[4]:
array([[False, False, False],
       [False, False, False],
       [False, False, False],
       [ True,  True,  True],
       [ True,  True, False],
       [False,  True,  True],
       [False,  True,  True]])