Python NumPy For Your Grandma | Section 2.5 | Basic Math
- 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
- Intermediate Array Stuff
3.4 boolean indexing
- Common Operations
4.2 Math Funcs
4.3 all and any
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.