NumPy is the most important scientific programming Python package.


In [1]:
import numpy as np
np.eye(3) # identity matrix


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

NumPy comes with a powerful and expressive array type.


In [2]:
# Defining an array
my_array = np.array([[0, 1], [2, 3]])
my_array


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

In [3]:
# Slicing
print my_array[0, :]
print my_array[1, :]
print my_array[:, 0]
print my_array[:, 1]


[0 1]
[2 3]
[0 2]
[1 3]

In [4]:
# Multiplication
my_array.dot(my_array)


Out[4]:
array([[ 2,  3],
       [ 6, 11]])

In [5]:
# Solving a linear equation
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
print np.linalg.solve(a, b)


[ 2.  3.]

In [6]:
# Finding the pseudoinverse
np.linalg.pinv(my_array)


Out[6]:
array([[ -1.50000000e+00,   5.00000000e-01],
       [  1.00000000e+00,   5.55111512e-17]])

In [7]:
# Transposing
my_array.T


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

In [8]:
# Vector operations
my_vector = np.array([1, 2, 3])
print my_vector

# Dot product
print my_vector.dot(my_vector.T)

# Cross product
print np.cross(my_vector.T, my_vector)


[1 2 3]
14
[0 0 0]