Python NumPy For Your Grandma | Section 2.5 | Basic Math


Course Contents

  1. Introduction
  2. NumPy Arrays
    2.1 What’s A NumPy Array
    2.2 Creating NumPy Arrays
    2.3 Indexing And Modifying 1-D Arrays
    2.4 Indexing And Modifying Multidimensional Arrays
    2.5 Basic Math
  3. Intermediate Array Stuff
    3.1 Broadcasting
    3.2 newaxis
    3.3 reshape
    3.4 boolean indexing
    3.5 nan
    3.6 infinity
    3.7 random
  4. Common Operations
    4.1 where
    4.2 Math Funcs
    4.3 all and any
    4.4 concatenate
    4.5 Stacking
    4.6 Sorting
    4.7 unique
  5. Challenges

This video covers basic math operations for NumPy arrays like addition, subtraction, multiplication, division, and matrix multiplication.


import numpy as np

# make 2x2 arrays
foo = np.array([[4,3], [1,0]])
bar = np.array([[1,2], [3,4]])

# addition
foo + bar

# subtraction
foo - bar

# multiplication
foo * bar

# division
foo / bar

# matrix multiplication, you can use the @ operator
foo @ bar


Now let’s see some basic math operations using these 2x2 arrays. With numpy, you can

  • add arrays
  • subtract arrays
  • multiply arrays
  • divide arrays

and do other basic math operations pretty seamlessly if your arrays have the same shape.

It’s important to realize that these operations happen element-wise. For example, when we multiply foo times bar, the first element in the result is the product of the first element in foo times the first element in bar. This is different than matrix multiplication where the first element of the result would be equal to the dot product of the first row of foo with the first column of bar.
If you want to do standard matrix multiplication, you can use the ‘at’ operator.
In a future section, we’ll see how you can use broadcasting to do math on arrays with different shapes.