0% found this document useful (0 votes)
16 views

Numpy Matplot

The document discusses Python libraries NumPy and Matplotlib. NumPy is a library for numerical and scientific computing that allows for multi-dimensional arrays and matrix operations. It contains ndarray objects that store data and associated attributes like shape, size, type. Matplotlib is a plotting library that can be used with NumPy to visualize data. The document then covers how to import, create, and access NumPy arrays through various functions and attributes.

Uploaded by

abzjkr
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Numpy Matplot

The document discusses Python libraries NumPy and Matplotlib. NumPy is a library for numerical and scientific computing that allows for multi-dimensional arrays and matrix operations. It contains ndarray objects that store data and associated attributes like shape, size, type. Matplotlib is a plotting library that can be used with NumPy to visualize data. The document then covers how to import, create, and access NumPy arrays through various functions and attributes.

Uploaded by

abzjkr
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

11

Python Libraries
Numpy(Numerical Python), Matplotlib

 NumPy (Numerical Python) is an open source library available in Python that


aids in mathematical, scientific, engineering, & data science programming.
 NumPy is an incredible library to perform mathematical & statistical
operations.
 It works perfectly well for multi-dimensional arrays & matrix multiplication
 Matplotlib is a plotting library for the Python & its numerical mathematics
extension NumPy.
 It provides an object-oriented API for embedding plots into applications using
general-purpose GUI toolkits like tkinter, wxPython, Qt, or GTK+

Importing the NumPy module

There are several ways to import NumPy. The standard approach is to use a simple
import statement:
12

import numpy o import numpy as from numpy import *


or
numpy.x r np x
np.x
 NumPy Arrays
o NumPy arrays are a bit like Python lists, & access elements using square
brackets but still very much different at the same time.
o NumPys main object is the homogeneous multidimensional array.

o It is a table of elements (usually numbers), all of the same type, indexed


by a tuple of +ve integers.
o In NumPy dimensions are called axes.
o The number of axes is rank.

For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank


1, because it has one axis. That axis has a length of 3.
In example pictured below, the array has rank 2 (it is 2-dimensional). The 1st
dimension (axis) has a length of 2, the 2nd dimension has a length of 3.
 Numpy’s array is called ndarray.
 It is also known as array.
Note that numpy.array is not the same as the Standard Python Library class
array.array, which only handles one-dimensional arrays & offers less
functionality.
Eg:
import numpy as np import numpy as np
a = np.array([[1, 2], [3,
a = np.array([[1, 2], [3,
4]]) a
4]]) print a
output or
array[[1, 2] output
[3, 4]] [[1, 2]
[3, 4]]
Important attributes of an ndarray objects
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
13

The number of axes (dimensions) of the array. The


number of dimensions is referred to as rank.
# n nos
ndarray.ndim import numpy as np
a = np.arange(20)
print a
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

ndarray.shape The dimensions of the array. This is a tuple of integers


14

indicating the size of the array in each dimension. For a


matrix with n rows & m columns, shape will be (n, m).
The length of the shape tuple is therefore the rank, or
number of dimensions, ndim.
Eg:
import numpy as np a=np.array([[1,2,3],
[4,5,6]])
print a.shape
(2, 3)
The total number of elements of the array. This is equal
to the product of the elements of shape.
ndarray.size Eg:
a.size
output
15
An object describing the type of the elements in the
array. One can create or specify using standard Python
types. Additionally NumPy provides types of its own.
ndarray.dtype Eg: numpy.int32, numpy.int16,& numpy.float64.
Eg:
a.dtype
output
int32
The size in bytes of each element of the array.
Eg: An array of elements of type float64 has itemsize 8
(=64/8), while one of type complex32 has itemsize 4
(=32/8).
ndarray.itemsize Eg1: Eg2:
a.itemsize a.dtype.itemsize
output output
4 4
ndarray.itemsize is equivalent
to ndarray.dtype.itemsize
The buffer containing the actual elements of the array.
Normally, we this attribute because we
will access the elements in an array using indexing
ndarray.data
facilities.
Eg:
a.data
<memory at 0x03F255D0>
Eg:
import numpy as np a.itemsize
a = np.arange(15).reshape(3, 5) 8
a a.size
array([[ 0, 1, 2, 3, 4], 15
[ 5, 6, 7, 8, 9],
type(a)
[10, 11, 12, 13, 14]])
15

a.shape <type 'numpy.ndarray'>


(3, 5) b = np.array([6, 7, 8])
a.ndim b
2
a.dtype.name array([6, 7, 8]) type(b)
'int64' <type 'numpy.ndarray'>

Array Creation
There are several ways to create arrays.
For example, you can create an array from a regular Python list or tuple using
the array function. The type of the resulting array is deduced from the type of the
elements in the sequences.
import numpy as np a.dtype
a = np.array([2,3,4]) dtype('int64')
a b = np.array([1.2, 3.5, 5.1])
array([2, 3, 4])
b.dtype
print(a)
[2 3 4] dtype ('float64')

A frequent error consists in calling array with multiple numeric arguments, rat
her than providing a single list of numbers as an argument.
a = np.array(1,2,3,4) # WRONG
a = np.array([1,2,3,4]) # RIGHT

array transforms sequences of sequences into 2-dimensional arrays,


sequences of sequences of sequences into 3-dimensional arrays, & so on.

b = np.array([(1.5,2,3), (4,5,6)]) b = np.array([(1.5,2,3), (4,5,6)])


b print(b)
array([[ 1.5, 2. , 3. ], [[ 1.5 2. 3. ]
[ 4. , 5. , 6. ]]) [ 4. 5. 6. ]]
The type of the array can also be explicitly specified at creation time:

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )


>>> c
array([[ 1.+0.j, 2.+0.j],
[ 3.+0.j, 4.+0.j]])
>>> print(c)
[[ 1.+0.j 2.+0.j]
[ 3.+0.j 4.+0.j]]
Often, the elements of an array are originally unknown, but its size is
known. Hence, NumPy offers several functions to create arrays with initial
16

placeholder content. These minimize the necessity of growing arrays, an expensive


operation.
The function empty creates an array whose initial content is random &
depends on the state of the memory.
By default, the dtype of the created array is float64.
import numpy as np
a = np.zeros((2,2)) #The function zeros creates an array full of zeros.
print(a)
[[ 0. 0.]
[ 0. 0.]]
b = np.ones((1,2)) #The function ones creates an array full of ones.
print(b)
[[ 1. 1.]]
np.ones( (2,3), dtype=np.int16)
array([[1, 1, 1],
[1, 1, 1]], dtype=int16)
c = np.full((2,2), 7)
print(c)
[[7 7]
[7 7]]
d = np.eye(2) # Create a 2x2 identity
matrix print(d)
[[ 1. 0.]
[ 0. 1.]]

np.empty( (2,2) ) # the function empty creates an array whose initial conte
nt is
# random & depends on the state of the memor
y
array([[4.16254416e+196, 6.58798947e-293],
[6.68007707e-294, 1.99178933e-306]])

To create sequences of numbers, NumPy provides a function analogous


to range that returns arrays instead of lists:

np.arange(10, 30, 5 ) # start, stop , step


array([10, 15, 20, 25])
np.arange( 0, 2, 0.3 ) # it accepts float arguments
array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
When arange is used with floating point arguments, it is generally not
possible to predict the number of elements obtained, due to the finite
floating point precision.
For this reason, it is usually better to use the function linspace that receives
as an argument the number of elements that we want, instead of the step:
np.linspace( 0, 2, 6 ) # 6 numbers from 0 to 2
array([ 0. , 0.4, 0.8, 1.2, 1.6, 2. ])
17

numpy.asarray()

numpy.asarray()function is used when we want to convert input to an array.


Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists &
ndarrays.
import numpy as np list1 = [1, 3, 5, 7, 9]
print ("Input list : ", list1) array1 = np.asarray(list1) print
Input list : [1, 3, ("output
5, 7, 9] array: ", array1)
output array: [1 3 5 7 9]

Printing Arrays

When you print an array, NumPy displays it in a similar way to nested lists, but with
the following layout:
the last axis is printed from left to right,
the 2nd-to-last is printed from top to bottom,
the rest are also printed from top to bottom, with each slice separated from the
next by an empty line.
1-dimensional arrays are printed as rows,
bi-dimensional as matrices &
tri-dimensional as lists of matrices.
a = np.arange(6) # 1d array c = np.arange(24).reshape(2,3,4) # 3d array
print(a) print(c)
[0 1 2 3 4 5] [ [ [ 0 1 2 3]
b = np.arange(12).reshape(4,3) # 2d array [ 4 5 6 7]
print(b) [ 8 9 10 11] ]
[[ 0 1 2]
[ 3 4 5] [ [12 13 14 15]
[ 6 7 8] [16 17 18 19]
[ 9 10 11]] [20 21 22 23] ] ]
# numpy.reshape()
import numpy as # Constructs 3D array
np a = a = np.arange(8).reshape(2, 2, 2)
np.arange(8) print("array reshaped to 3D :", a)
print("a : \n", a) Original array reshaped to 3D :
a : [0 1 2 3 4 5 6 7] [[[0 1]
# shape array with 2 rows & 4 [2 3]]
columns a =
np.arange(8).reshape(2, d with
4) 2 x 4
:
print("reshaped with 2 x 4 cols:", a) [ [4 5]
reshape[[0 1 2 3] [6 7]]]

[4 5 6 7]]
If an array is too large to be printed, NumPy automatically skips the central part
of the array and only prints the corners:

print(np.arange(10000)) print(np.arange(10000).reshape(100,100))
[ 0 1 2 ..., 9997 9998 9999]
[[ 0 1 2 ..., 97 98 99]
[ 100 101 102 ..., 197 198 199]
18

[ 200 201 202 ..., 297 298 299]


...,
[9700 9701 9702 ..., 9797 9798 9799]
[9800 9801 9802 ..., 9897 9898 9899]
[9900 9901 9902 ..., 9997 9998 9999]]

Indexing & Slicing

1-dimensional arrays can be indexed, sliced & iterated over, much like lists
& other Python sequences.

NumPy offers several ways to index into arrays.

Array Indexing
The important thing to remember is that indexing in python starts at zero.

x1 = np.array([4, 3, 4, 4, 8, 4])
x1 # array([4, 3, 4, 4, 8, 4])
x1[0] #access value to index zero
4
x1[4] #access 5th value
8
x1[-1] #get the last value
4
x1[-2] #get the 2nd last value
8
#in a multidimensional array, we need to specify row & column index
x2

array([[3, 7, 5, 5],
[0, 1, 5, 9],
[3, 0, 5, 0]])

x2[2,1] #3rd row & 2nd column value


0
x2[2,-1] #3rd row & last value from the 3rd column
0
x2[0,0] = 12 #replace value at 0,0
x2

array([[12, 7, 5, 5],
[ 0, 1, 5, 9],
[ 3, 0, 5, 0]])
Array Slicing
Similar to Python lists, NumPy arrays can be sliced. Since arrays may be
mu ltidimensional, you must specify a slice for each dimension of the array:
x = np.arange(10)
x# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[:5]#from start to 4th position
19

array([0, 1, 2, 3, 4])
x[4:]#from 4th position to last
array([4, 5, 6, 7, 8, 9])
x[4:7]#from 4th to 6th position
array([4, 5, 6])
x[ : : 2]#return elements at even place
array([0, 2, 4, 6, 8])
x[1::2]#return elements from 1st position step by 2
array([1, 3, 5, 7, 9])
x[::-1]#reverse the array
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

Multidimensional arrays can have one index per axis. These indices are given in
a tuple separated by commas:
a = np.arange(10)
print a #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2,7,2) # start, stop, step
print a[s] # [2 4 6]
ndarray object is prepared by arange() function. Then a slice object is defined
with start, stop, & step values 2, 7, & 2 respectively. When this slice object is
passed to the ndarray, a part of it starting with index 2 up to 7 with a step of
2 is sliced.
a = np.arange(10)
print a #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b=a[2:7:2] # start : stop : step
print(b) # [2 4 6]
Data types
Every numpy array is a grid of elements of the same type. NumPy
provides a large set of numeric data types that you can use to construct
arrays.
NumPy tries to guess a data type when you create an array, but
functions that construct arrays usually also include an optional argument to
explicitly specify the datatype. Here is an example:
import numpy as np x = np.array([1,
x = np.array([1.0,
2]) print(x) 2.0])
#[1 2] print(x.dtype)
print(x.dtype) # float64
#int32 x = np.array([1, 2], dtype=np.int64)
print(x.dtype)
# int64

Array math
Basic mathematical functions operate elementwise on arrays, and are
available both as operator overloads and as functions in the numpy module:
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise addition; both produce the
array print(np.add(x, y))
[[ 6. 8.]
print(x + y)
[ 10. 12.]]
[[ 6. 8.]
20

[ 10. 12.]]
# Elementwise difference
print(np.subtract(x, y))
print(x - y) [[-4. -4.]
[[-4. -4.] [-4. -4.]]
[-4. -4.]]
# Element-wise product print(np.multiply(x, y))
print(x * y)
[[ 5.012.0]
[21.032.0]]
[[ 5.012.0]
[21.032.0]]
is element-wise multiplication, not matrix multiplication
*

We instead use the dot function to compute inner products of vectors, to


multiply a vector by a matrix, and to multiply matrices.dot is available both as
a function in the numpy module and as an instance method of array objects:
#matrix multiplication matrix x
import numpy as np print("\ [[2 2]
nmatrix x\n") [2 2]]
x = np.array([[2,2],[2,2]])
print (x) print("\ matrix y
nmatrix y\n") [[2 2]
y = np.array([[2,2],[2,2]]) [2 2]]
print(y)
print("\n matrix multiplication\n") matrix multiplication
[[8 8]
z=x.dot(y) # z=np.dot(x,y) [8 8]]
print(z)

Broadcasting

The term broadcasting refers to the ability of NumPy to treat arrays of


different shapes during arithmetic operations. Arithmetic operations on arrays
are usually done on corresponding elements. If 2 arrays are of exactly the
same shape, then these operations are smoothly performed.
import numpy as np [10 40 90 160]
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c=a*b
print c
If the dimensions of 2 arrays are dissimilar, element-to-element
operations are not possible. However, operations on arrays of dissimilar
shapes are still possible in NumPy, because of the broadcasting capability.
The smaller array is broadcast to the size of the larger array so that they have
compatible shapes.
21

a = np.array([[1, 2], [3, 4], [5, 6]],


float) b = np.array([-1, 3], float)
print a print b
([[ 1., 2.], ([-1., 3.])
[ 3., 4.], print (a + b)
[ 5., 6.]]) ([[ 0., 5.],
[ 2., 7.],
[4.,9.]])
Here, the one-dimensional array b was broadcasted to a 2-dimensional array that
matched the size of a. In essence, b was repeated for each item in a, as if it were
given by
([[-1., 3.],
[-1., 3.],
[-1., 3.]])
Basic array operations
a = np.array([2, 4, 3],
float)
a.sum() # 9.0 a.prod() #24.0
A number of routines enable computation of statistical quantities in array
datasets, such as the mean (average), variance, & standard deviation:
a = np.array([2, 1, 9], float) a.mean() #4.0
a.std() # 3.5590260840104371 a.var() #12.666666666666666
a.min() # 1.0 a.max() #9.0
np.median(a) #1.0
a = np.array([6, 2, 5, -1, 0], a = np.array([6, 2, 5, -1, 0],
float) sorted(a) float) a.sort()
#[-1.0, 0.0, 2.0, 5.0, 6.0] a #array([-1., 0., 2., 5., 6.])

Trigonometric functions

np.sin(a) # array([-0.00885131, -0.8462204 , -0.90557836, -0.13235175])


np.cos(a) # array([-0.99996083, -0.53283302, 0.42417901, 0.99120281])
np.tan(a) # array([ 0.00885166, 1.58815308, -2.1348967 , -0.13352641])
a=np.array([2.3,3.4,2.1])
np.around(a) # array([2., 3., 2.])
np.ceil(a) # array([3., 4., 3.])
np.floor(a) # array([2., 3., 2.])

Matplotlib
Data visualization is the presentation of data in a pictorial or graphical
format. Matplotlib is a Python 2D plotting library/package which
produces publication quality figures in a variety of hardcopy formats &
interactive environments across platforms.
One of the most popular uses for Python is data analysis.
Naturally, data scientists want a way to visualize their data. Either they
are wanted to see it for themselves to get a better grasp of the data, or
they want to display the data to convey their results to someone.
With Matplotlib, the most popular graphing and data visualization
module for Python, this is very simplistic to do.
22

In order to get the Matplotlib, you should first head to Matplotlib.org &
download the version that matches your version of Python. Once you have
Matplotlib installed, be sure to open up a terminal or a script, type:
import Matplotlib
Eg1:
from matplotlib import pyplot as plt plt.plot([1,2,3],[4,5,1]) #plot(x values, y values) plt.show(

Eg2:
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

pythonprogramming.net/downloads/style.zip
Then, extract that, & move the styles folder within it to
c:/python34/matplotlib, where python34 is your python version. If you are
not on windows, just make sure the styles folder is in the root matplotlib
package folder.
Types Of
Plots Bar
Graph
Histogram
Scatter Plot
Area Plot
Pie Chart
#Bar graph
from matplotlib import pyplot as
plt
x1 = [5,8,10]
y1 = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.bar
(x1,y1,color='b',align='center')
plt.bar(x2, y2, color='g',
align='center')
plt.title('Bar Plot')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
23

#scatter plot
from matplotlib import pyplot as plt
x1 = [5,8,10]
y1 = [12,16,6]
x2 = [6,9,11]
y2 = [6,15,7]
plt.scatter(x1, y1,color='r')
plt.scatter(x2, y2, color='g')
plt.title('Scatter plot')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

subplot()

The Matplotlib subplot() function can be called to plot two or more


plots in one figure.
Matplotlib supports all kind of subplots including 2x1 vertical, 2x1
horizontal or a 2x2 grid.
The subplot() function allows you to plot different things in the same figure.
In the following script, sine and cosine values are plotted.
subplot(m,n,p)
divides the current figure into an m-by-n grid & creates axes in the position specified
by p.
MATLAB numbers subplot positions by row. The 1st subplot is the 1st column of the
first row, the 2nd subplot is the second column of the first row, and so on. If axes
exist in the specified position, then this command makes the axes the current axes.

Eg:

subplot(2,2,1) - 2 row, 2 column & 1st subplot

subplot(2,2,2) - 2 row, 2 column & 2nd subplot

subplot(2,2,1) - 2 row, 2 column & 1st subplot


24

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.subplot(2, 1, 1) #2 rows,1 col,1st plot
plt.plot(x, y_sin)
plt.title('Sine')
plt.subplot(2, 1, 2) #2 rows,1 col,2nd plot
plt.plot(x, y_cos) plt.title('Cosine') plt.show()

SciPy(Scientific Python)

SciPy (pronounced "Sigh Pie") is an open source Python library used for
scientific computing & technical computing.
The SciPy library depends on Numpy, which provides convenient & fast
N- dimensional array manipulation.
SciPy is a library of algorithms and mathematical tools built to work with
NumPy arrays.
It provides many user-friendly & efficient numerical practices such as
routines for numerical integration & optimization.
SciPy contains modules for optimization, linear algebra, integration,
interpolation, special functions, FFT, signal and image processing, &
other tasks common in science & engineering.
Linear Equations
numpy.linalg.solve(a, b)

Solve a linear matrix equation, or system of linear scalar equations.

The scipy.linalg.solve feature solves the linear equation


a * x + b * y = Z, for the unknown x, y values.
As an example, assume that it is desired to solve the following simultaneous
equations.
x + 3y + 5z =
10 2x + 5y + z
= 8 2x + 3y +
8z = 3

array.

a = np.array([[1, 3, 5], [2,5,1], [2, 3, 8]])

b = np.array([10, 8, 3])

x = linalg.solve(a, b)

You might also like