Tech With Tim Logo
Go back

Array Math

Array Math

Another reason that numpy is so useful is because of its extensive implementation for array operations and math. Numpy has tons of functions that save us tons of time and can perform operations very quickly

The following operations are supported on numpy arrays. They perform whats known as element-wise operations.

  • addition: + or np.add()
  • subtraction: - or np.subtract()
  • multiplication: * or np.multiply()
  • division: / or np.divide()
  • square root: np.sqrt()
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])

x + y  # -> array([[ 6,  8],
#                  [10, 12]])

x - y  # -> array([[-4, -4],
#                  [-4, -4]])

x * y  # -> array([[ 5, 12],
#                  [21, 32]])

x / y  # -> array([[0.2       , 0.33333333],
#                  [0.42857143, 0.5       ]])

np.sqrt(x)  # -> array([[1.        , 1.41421356],
#                       [1.73205081, 2.        ]])

To take the dot product of two arrays we can use .dot().

import numpy as np
v = np.array([9,10])
w = np.array([11,13])

v.dot(w) # -> 229
w.dot(v) # -> 229

np.dot(v, w) # -> 229

When we take the dot product of two arrays of the same size we get a scalar. Otherwise we get what's called an inner product.

To transpose a matrix or array we can use .T.

import numpy as np
v = np.array([[9,10], [98, 67]])

v.T  # ->  array([[ 9, 98],
#                 [10, 67]])

To take the sum of an array we can use np.sum(axis=).

import numpy as np
v = np.array([[9,10], [98, 67]])

np.sum(v)  # -> 184
np.sum(v, axis=0)  # array([107,  77]), this gives us the sum of the columns stored in an array

To read more about numpy and see everything it has to offer click here.

Design & Development by Ibezio Logo

Join Tim's Coding Corner Newsletter

Register and I'll give you an entire FREE guide on How To Make Money From Coding just to prove to you how much value is coming. Check your email for immediate access.

And if that wasn't enough... each email will contain free coding challenges, project ideas and software engineering insights and tips.

We won't send you spam, just free value. Unsubscribe at any time.