Numerical operations on arrays
%matplotlib inline
import matplotlib.pyplot as plt # the tidy way
import pandas as pd
import numpy as np
5. Elementwise operations
Basic operations
With scalars:
>> a = np.array([1, 2, 3, 4])
>> a + 1
array([2, 3, 4, 5])
>> 2**a
array([ 2, 4, 8, 16])
All arithmetic operates elementwise:
>> b = np.ones(4) + 1
>> a - b
array([-1., 0., 1., 2.])
>> a * b
array([2., 4., 6., 8.])
These operations are of course much faster than if you did them in pure python:
>> j = np.arange(5)
>> 2**(j + 1) - j
array([ 2, 3, 6, 13, 28])
>> a = np.arange(10000)
>> %timeit a + 1
3.25 μs ± 366 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>> l = range(10000)
>> %timeit [i+1 for i in l]
592 μs ± 51.4 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Array multiplication is not matrix multiplication:
>> c = np.ones((3, 3))
>> c * c # NOT matrix multiplication!
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
Matrix multiplication:
>> c.dot(c)
array([[3., 3., 3.],
[3., 3., 3.],
[3., 3., 3.]])
Exercise: Elementwise operations
Try simple arithmetic elementwise operations: add even elements with odd elements
Time them against their pure python counterparts using %timeit.
Generate:
[20, 21, 22, 23, 2*4]
a_j = 2^(3j) - j
Other operations
Comparisons:
>> a = np.array([1, 2, 3, 4])
>> b = np.array([4, 2, 2, 4])
>> a == b
array([False, True, False, True])
>> a > b
array([False, False, True, False])
>> a = np.array([1, 2, 3, 4])
>> b = np.array([4, 2, 2, 4])
>> c = np.array([1, 2, 3, 4])
>> np.array_equal(a, b)
False
>> np.array_equal(a, c)
True
Logical operations:
>> a = np.array([1, 1, 0, 0], dtype=bool)
>> b = np.array([1, 0, 1, 0], dtype=bool)
>> np.logical_or(a, b)
array([ True, True, True, False])
>> np.logical_and(a, b)
array([ True, False, False, False])
Transcendental functions:
>> a = np.arange(5)
>> np.sin(a)
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])
>> np.log(a)
array([ -inf, 0. , 0.69314718, 1.09861229, 1.38629436])
>> np.exp(a)
array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003])
Shape mismatches
>> a = np.arange(4)
>> a + np.array([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4) (2)
Transposition:
>> a = np.triu(np.ones((3, 3)), 1) # see help(np.triu)
>> a
array([[0., 1., 1.],
[0., 0., 1.],
[0., 0., 0.]])
>> a.T
array([[0., 0., 0.],
[1., 0., 0.],
[1., 1., 0.]])
Exercise other operations
Look at the help for np.allclose. When might this be useful?
Look at the help for np.triu and np.tril