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.
In [2]:
import numpy as np
a = np.array([1, 2, 3])
print ( type(a) )
print( a.shape ) #dimension of the array
In [3]:
print (a)
Now we define a two-dimensional array of size 2$\times$3
In [4]:
b = np.array([[1, 2, 3], [4, 5, 6]])
print ( b.shape )
In [5]:
print( b )
Any time you need help you can write "numpy.array?", you may initialize a matrix using "numpy.full"
In [6]:
print( np.full((2, 3), 7.0) )
This initializes a 2$\times$3 with value float 7.0. try other functions like numpy.zeros, numpy.ones, and numpy.eye
In [7]:
print( np.zeros((3, 3)) )
print( np.ones((3,4)) )
In [8]:
print( np.eye(4) ) #gives identity matrix
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 [9]:
#import numpy as np
a = np.array([[1, 2], [3, 4], [5, 6]])
print( a )
In [10]:
print( a>2 )
In [11]:
print( a[a>2] )
In [12]:
myarray = np.eye(5)
print( myarray == 1 )
In [13]:
print( myarray[myarray == 1] )
In [14]:
print( len(myarray) )
print( range(1,len(myarray)+1) )
Exercise
Produce an identity matrix of size 10 and
replace the diagonal elements with 1 to 10.
In [15]:
myarray = np.eye(10)
myarray[myarray == 1] = range(1, len(myarray)+1)
print( myarray )
Replace the non-zero elements of the last matrix with increasing powers of 2.
In [16]:
type(myarray)
Out[16]:
In [17]:
vector = (range(1, len(myarray)+1))
(np.array(vector))**2
Out[17]:
In [18]:
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) )
In [20]:
print( x - y )
print( np.subtract(x, y) )
In [21]:
print( x * y )
print( np.multiply(x, y) )
In [22]:
print( x / y )
print( np.divide(x, y) )
In [23]:
print( x.dot(y) )
print( np.dot(x, y) )
In [24]:
print( np.sum(x, axis = 1) )# on rows
print( np.sum(x, axis = 0) )# on columns
print( np.sum(x, axis = None) )#on both
print( np.sum(x) )# on both
In [25]:
print( x.T )
print( np.sum(x.T, axis = 0) )# gives sum over rows
#(and not columns even with axis=0)
In [26]:
print( x )
print( np.tile(x, (2, 3)) )
In [27]:
print( range(10) )
print( np.reshape(range(10), (2, 5) ) )
In [28]:
print( np.reshape(range(10),(5,2) ) )
Now let's use some image libraries and plot some pictures.