Numpy Intro¶
No need to say a lot here, NumPy is useful and you need it all over the place. In my favorite book about Data Science Jake says "provides an efficient interface to store and operate on dense data buffers." and then make a survey of many goodies fo numpy library. VanderPlas, Jake. Python Data Science Handbook. O'Reilly Media, 2016. I pulled many examples from this book.
Small Goodies¶
Broadcasting¶
This is about how matrices of different can be combined and what to do when they can't.
Rule 1
a = np.arange(3)
M = np.ones((2, 3))
a [0 1 2]
shp_a (3,)
M [[1. 1. 1.]
[1. 1. 1.]]
shp_M (2, 3)
Rule 1 & 2
a = np.arange(3).reshape((3, 1))
b = np.arange(3) # [0 1 2]
"""
a is:
[[0]
[1]
[2]]
"""
# shp_a (3, 1)
# shp_b (3,)
a + b
# array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
Example 3
Rule 3
M = np.ones((3, 2))
a = np.arange(3)
shp_M = (3, 2)
shp_a = (3,)
rule 1 pad the shape of a with ones at its leading side: a.shape -> (1, 3)
![bild.png](attachment:bild.png)
In [3]:
from IPython.display import Image
Image(r'C:\thisAKcode.github.io\Pelican\content\images\np_broadcasting.jpg', width = 600)
Out[3]:
Let's see how do you grab all values from 2d matrix and put it into a list.
In [6]:
import numpy as np
from sklearn import datasets
matrix = datasets.load_iris().data
column_0 = matrix[:,0] # [:,0] is [all_rows , column_0]
column_1 = matrix[:,1]
print(column_0, column_1)
In [4]:
import numpy as np
# notice stack
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.stack((a, b), axis=-1)
Out[4]:
In [ ]: