Introduction to arrays in numpy

The "numpy" is the efficient numerical computation library of python. We start with defining arrays and their basic manipulation. Arrays are like lists except their type is fixed for each element. The common types are int and float. We start with a one dimensional array of size 3.

1. General syntax


In [2]:
import numpy as np

a = np.array([1, 2, 3])  
print type(a)            
print a.shape


<type 'numpy.ndarray'>
(3,)

In [2]:
print a


[1 2 3]

Now we define a two-dimensional array of size 2$\times$3


In [3]:
b = np.array([[1, 2, 3], [4, 5, 6]])   
print b.shape


(2, 3)

In [4]:
print b[:, :]


[[1 2 3]
 [4 5 6]]

Any time you need help you can write "numpy.array?", you may initialize a matrix using "numpy.full"


In [5]:
print np.full((2, 3), 7.0)


[[ 7.  7.  7.]
 [ 7.  7.  7.]]

This initializes a 2$\times$3 with value float 7.0. try other functions like numpy.zeros, numpy.ones, and numpy.eye


In [6]:
print np.zeros((3, 3))


[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

In [7]:
print np.eye(4) #gives identity matrix


[[ 1.  0.  0.  0.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]

2. Boolean array indexing

Using the boolean array indexing you pick up the elements of an array. This type of indexing helps you to select the elements of an array that satisfy a condition. You must be aware that arrays in numpy is different from lists in python. However, we can convert a numeric list to a numpy array using np.array


In [8]:
import numpy as np
a = np.array([[1, 2], [3, 4], [5, 6]])
print (a>2)


[[False False]
 [ True  True]
 [ True  True]]

In [9]:
print a[a>2]


[3 4 5 6]

In [10]:
myarray=np.eye(10)
print myarray == 1


[[ True False False False False False False False False False]
 [False  True False False False False False False False False]
 [False False  True False False False False False False False]
 [False False False  True False False False False False False]
 [False False False False  True False False False False False]
 [False False False False False  True False False False False]
 [False False False False False False  True False False False]
 [False False False False False False False  True False False]
 [False False False False False False False False  True False]
 [False False False False False False False False False  True]]

In [11]:
print myarray[myarray == 1]


[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

In [12]:
print range(1,len(myarray)+1)


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Exercise
Produce an identity matrix of size 10 and

replace the diagonal elements with 1 to 10.


In [65]:
myarray=np.eye(10)
myarray[myarray == 1] = range(1, len(myarray)+1)
print myarray


[[  1.   0.   0.   0.   0.   0.   0.   0.   0.   0.]
 [  0.   2.   0.   0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   3.   0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.   4.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   5.   0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   6.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   7.   0.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.   8.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.   0.   9.   0.]
 [  0.   0.   0.   0.   0.   0.   0.   0.   0.  10.]]

Replace the non-zero elements of the last matrix with increasing powers of 2.


In [66]:
type(myarray)


Out[66]:
numpy.ndarray

In [67]:
vector = (range(1, len(myarray)+1))
(np.array(vector))**2


Out[67]:
array([  1,   4,   9,  16,  25,  36,  49,  64,  81, 100])

3. Matrix operations

Elementwise operation

Element-wise matrix operations are as follows

Take

$x=\left(\begin{array}{c c} 1&2\\3&4 \end{array}\right) ~~~~$ $y=\left(\begin{array}{c c} 5&6\\7&8 \end{array}\right)$


In [15]:
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
print x+y
print np.add(x, y)


[[  6.   8.]
 [ 10.  12.]]
[[  6.   8.]
 [ 10.  12.]]

In [16]:
print x-y
print np.subtract(x, y)


[[-4. -4.]
 [-4. -4.]]
[[-4. -4.]
 [-4. -4.]]

In [17]:
print x*y
print np.multiply(x, y)


[[  5.  12.]
 [ 21.  32.]]
[[  5.  12.]
 [ 21.  32.]]

In [18]:
print x/y
print np.divide(x, y)


[[ 0.2         0.33333333]
 [ 0.42857143  0.5       ]]
[[ 0.2         0.33333333]
 [ 0.42857143  0.5       ]]

Dot product

Matrix product is the "dot" operator. It can be used with only one, or two arguments


In [19]:
print x.dot(y)
print np.dot(x, y)


[[ 19.  22.]
 [ 43.  50.]]
[[ 19.  22.]
 [ 43.  50.]]

Matrix sum

The sum of a matrix can be implemented on rows, on columns, or on the total matrix.


In [20]:
print np.sum(x, axis = 1) # on rows 
print np.sum(x, axis = 0) # on columns
print np.sum(x, axis = None)  # on both


[ 3.  7.]
[ 4.  6.]
10.0

Matrix transpose

The function for transposing a matrix is .T


In [21]:
print x.T
print np.sum(x.T, axis = 0) # gives sum over rows (and not columns even with axis=0)


[[ 1.  3.]
 [ 2.  4.]]
[ 3.  7.]

Repeating a matrix

Repeating a matrix several times on rows and columns. This is a special case of the kronecker product


In [22]:
print np.tile(x, (2, 3))


[[ 1.  2.  1.  2.  1.  2.]
 [ 3.  4.  3.  4.  3.  4.]
 [ 1.  2.  1.  2.  1.  2.]
 [ 3.  4.  3.  4.  3.  4.]]

Reshaping a matrix


In [23]:
print range(10)
print np.reshape(range(10), (2, 5) )


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[[0 1 2 3 4]
 [5 6 7 8 9]]

In [24]:
print np.reshape(range(10),(5,2) )


[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Now let's use some image libraries and plot some pictures.


In [68]:
import matplotlib.pylab as plt

%matplotlib inline
img = plt.imread('../data/cat.jpg')

print img.shape
plt.imshow(img)


(400, 248, 3)
Out[68]:
<matplotlib.image.AxesImage at 0x10d01b790>

In [26]:
img_tinted = img * [0.0, 0.0, 1.0] #Red Green Blue 
print img_tinted.shape


(400, 248, 3)

In [27]:
plt.imshow(img_tinted)
plt.axis("off")


Out[27]:
(-0.5, 247.5, 399.5, -0.5)

In [28]:
img_tinted = img * [.27, .72, 0.07]
#img_tinted = img * [0.33, 0.33, 0.33]
print plt.imshow(img_tinted)


AxesImage(60,40;372x248)

In [29]:
print plt.imshow(np.sum(img_tinted, axis = 2))


AxesImage(60,40;372x248)

In [30]:
print plt.imshow(np.sum(img_tinted, axis=2), "gray")
plt.axis("off")


AxesImage(60,40;372x248)
Out[30]:
(-0.5, 247.5, 399.5, -0.5)