Numpy Basic

Numpy contains core routines for doing fast vector, matrix, and linear algebra-type operations in Python.


In [1]:
from numpy import *

Create array


In [2]:
array([1, 2, 3])


Out[2]:
array([1, 2, 3])

In [4]:
array([[0,1],[1,0]], 'f')


Out[4]:
array([[ 0.,  1.],
       [ 1.,  0.]], dtype=float32)

In [7]:
zeros((2, 3))


Out[7]:
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

In [8]:
identity(4)


Out[8]:
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])

Slicing


In [3]:
a = array([[0, 1, 2],[3, 4, 5]])
a


Out[3]:
array([[0, 1, 2],
       [3, 4, 5]])

In [4]:
a[0][0]


Out[4]:
0

In [5]:
a[0, 0]


Out[5]:
0

In [6]:
a[-1, 0]


Out[6]:
3

In [9]:
a[:, 1]


Out[9]:
array([1, 4])

In [8]:
a[0, :-1]


Out[8]:
array([0, 1])

Operation


In [10]:
0.5 * identity(2)


Out[10]:
array([[ 0.5,  0. ],
       [ 0. ,  0.5]])

In [11]:
identity(2) * 0.3 + array([[1, 0], [0, 0]])


Out[11]:
array([[ 1.3,  0. ],
       [ 0. ,  0.3]])

In [13]:
a0 = random.random((3,3))
a1 = random.random((3,3))

In [27]:
a0


Out[27]:
array([[ 0.84258984,  0.3678207 ,  0.87769208],
       [ 0.36909916,  0.42353022,  0.54863083],
       [ 0.08999536,  0.84152716,  0.51809746]])

In [28]:
a1


Out[28]:
array([[ 0.61921349,  0.97088541,  0.29053039],
       [ 0.55585198,  0.64892932,  0.76012311],
       [ 0.18926575,  0.147177  ,  0.28912562]])

In [29]:
a0 * a1


Out[29]:
array([[ 0.52174299,  0.35711175,  0.25499623],
       [ 0.2051645 ,  0.27484118,  0.41702697],
       [ 0.01703304,  0.12385344,  0.14979525]])

In [30]:
a0.dot(a1)


Out[30]:
array([[ 0.8923139 ,  1.1859239 ,  0.77815024],
       [ 0.56780831,  0.71394001,  0.58779286],
       [ 0.62154898,  0.70971886,  0.81560588]])

In [31]:
dot(a0, a1)


Out[31]:
array([[ 0.8923139 ,  1.1859239 ,  0.77815024],
       [ 0.56780831,  0.71394001,  0.58779286],
       [ 0.62154898,  0.70971886,  0.81560588]])

In [32]:
a0.T


Out[32]:
array([[ 0.84258984,  0.36909916,  0.08999536],
       [ 0.3678207 ,  0.42353022,  0.84152716],
       [ 0.87769208,  0.54863083,  0.51809746]])

In [15]:
linalg.pinv(a0).dot(a0)


Out[15]:
array([[  1.00000000e+00,  -8.88178420e-16,  -8.88178420e-16],
       [ -8.88178420e-16,   1.00000000e+00,  -1.77635684e-15],
       [  2.22044605e-15,   2.66453526e-15,   1.00000000e+00]])